题解 | 求二叉树的层序遍历

求二叉树的层序遍历

https://www.nowcoder.com/practice/04a5560e43e24e9db4595865dc9c63a3

/**
 * struct TreeNode {
 *	int val;
 *	struct TreeNode *left;
 *	struct TreeNode *right;
 *	TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 * };
 */
class Solution {
public:
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     * 
     * @param root TreeNode类 
     * @return int整型vector<vector<>>
     */
    vector<vector<int> > levelOrder(TreeNode* root) {
        vector<vector<int> > res;
        vector<int> test;
        if(root==nullptr)
        {
            return res;
        }
        queue<TreeNode*> q;
        TreeNode* cur = root;
        q.push(root);
        while(!q.empty())
        {
            int n=q.size();//上一次队列中元素的数目
            for(int i=0;i<n;i++)
            {
                cur=q.front();
                test.push_back(cur->val);
                if(cur->left!=nullptr)
                {
                    q.push(cur->left);
                }
                if(cur->right!=nullptr)
                {
                    q.push(cur->right);
                }
                q.pop();
            }
            res.push_back(test);
            test.clear();
        }
        return res;
    }
};

全部评论

相关推荐

评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务