0
点赞
收藏
分享

微信扫一扫

NC15 求二叉树的层序遍历(c++)

眸晓 2022-03-11 阅读 40

在这里插入图片描述
在这里插入图片描述

/**
 * 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>>res;
        if(!root)return res;
        queue<TreeNode*>q;
        q.push(root);
        while(!q.empty()){
            vector<int>subres;
            int count = q.size();
            while(count--){
                TreeNode* temp = q.front();
                subres.push_back(temp->val);
                q.pop();
                if(temp->left){
                    q.push(temp->left);
                }
                if(temp -> right){
                    q.push(temp->right);
                }
            }
            if(subres.size() > 0){
                res.push_back(subres);
            }
        }
        return res;
    }
};
举报

相关推荐

0 条评论