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

求二叉树的层序遍历

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

class Solution {
public:
    vector<vector<int> > levelOrder(TreeNode* root) {
        // write code here
        vector<vector<int> > ret;
        queue<TreeNode*> q;
        if(root == nullptr) return ret;
        q.push(root);
        while(!q.empty())
        {
            int n = q.size();
            vector<int> v;
            for(int i=0;i<n;++i)
            {
                TreeNode* temp=q.front();
                q.pop();
                v.push_back(temp->val);
                if(temp->left)
                    q.push(temp->left);
                if(temp->right)
                    q.push(temp->right);
            }
            ret.push_back(v);
        }
        return ret;
    }
};

全部评论

相关推荐

点赞 评论 收藏
转发
点赞 收藏 评论
分享
牛客网
牛客企业服务