牛客题霸 [ 求二叉树的层序遍历] C++题解/答案

题目描述

给定一个二叉树,返回该二叉树层序遍历的结果,(从左到右,一层一层地遍历)
例如:
给定的二叉树是{3,9,20,#,#,15,7},

该二叉树层序遍历的结果是
[
[3],
[9,20],
[15,7]
]

代码:

/** * struct TreeNode { * int val; * struct TreeNode *left; * struct TreeNode *right; * }; */

class Solution {
   
public:
    /** * * @param root TreeNode类 * @return int整型vector<vector<>> */
    vector<vector<int> > levelOrder(TreeNode* root) {
   
        // write code here
        vector<vector<int>>vec;
        if(root==NULL)return vec;
        queue<TreeNode*>q;
        queue<int>lev;
        q.push(root);
        lev.push(0);
        TreeNode*p;
        int top=0;
        while(!q.empty()){
   
            p=q.front();
            top=lev.front();
            q.pop();
            lev.pop();
             
            if(vec.size()<top+1){
   
                vector<int>vt;
                vec.push_back(vt);
            }
            
            vec[top].push_back(p->val);
            if(p->left!=NULL)q.push(p->left),lev.push(top+1);
            if(p->right!=NULL)q.push(p->right),lev.push(top+1);
        }
        return vec;
    }
};