力扣 面試題32 - I. 從上到下打印二叉樹 bfs

https://leetcode-cn.com/problems/cong-shang-dao-xia-da-yin-er-cha-shu-lcof/

在這裏插入圖片描述

思路:bfsbfs即可,每次處理一整個層次。

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    vector<int> levelOrder(TreeNode* root) {
        vector<int> ans;
        if(root==NULL)
            return ans;
        queue<TreeNode*> q;
        q.push(root);
        TreeNode *fon;
        int siz;
        while(!q.empty())
        {
            siz=q.size();
            while(siz--)
            {
                fon=q.front();
                q.pop();
                ans.push_back(fon->val);
                if(fon->left!=NULL)
                    q.push(fon->left);
                if(fon->right!=NULL)
                    q.push(fon->right);
            }
        }
        return ans;
    }
};
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章