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

求二叉树的层序遍历

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

 int sublevel(TreeNode* tr,vector<vector<int>>& res,int ind){
    if(!tr)
        return 0;
    if(res.size()<ind){
        vector<int> level;
        level.push_back(tr->val);
        res.push_back(level);
    }//输出结果res层数小于当前层数指标ind,则创建第ind层res[ind-1],并存入val;
    else {
        res[ind-1].push_back(tr->val);
    }//已经创建res的ind层数,直接存入。
    sublevel(tr->left,res,ind+1);//处理下一层(先左);
    sublevel(tr->right,res,ind+1);
    
    return 0;
 }

class Solution {
public:
    vector<vector<int> > levelOrder(TreeNode* root) {
        vector<vector<int>> res;
        int ind=1;
        sublevel(root,res,ind);//层层迭代;
        return res;
    }
};

全部评论

相关推荐

评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务