其他分享
首页 > 其他分享> > LeetCode 102 Binary Tree Level Order Traversal 层序BFS

LeetCode 102 Binary Tree Level Order Traversal 层序BFS

作者:互联网

Given the root of a binary tree, return the level order traversal of its nodes' values. (i.e., from left to right, level by level).

Solution

用 \(BFS\) 即可,每次将该层的节点 \(pop\), 然后 \(push\) 其子数的节点

点击查看代码
/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
private:
    vector<vector<int>> ans;
    queue<TreeNode*> q;
    
    
    
public:
    vector<vector<int>> levelOrder(TreeNode* root) {
        if(!root) return ans;
        q.push(root);
        while(!q.empty()){
            int sz = q.size();
            vector<int> tmp;
            for(int i=0;i<sz;i++){
                auto f = q.front(); q.pop();
                tmp.push_back(f->val);
                if(f->left)q.push(f->left);
                if(f->right)q.push(f->right);
            }
            ans.push_back(tmp);
        }
        return ans;
    }
};

标签:Binary,right,TreeNode,Level,int,层序,nullptr,push,left
来源: https://www.cnblogs.com/xinyu04/p/16513776.html