题解 | #把二叉树打印成多行#

把二叉树打印成多行

https://www.nowcoder.com/practice/445c44d982d04483b04a54f298796288

class Solution {
public:
        vector<vector<int> > res;
        int max=0;   //max记录树的深度
        void findt(TreeNode* p,int t){   //判断树的深度
            if(p==NULL) return;
            findt(p->left,t+1);
            findt(p->right,t+1);
            if(t>max) max=t;
            return;
        }

        void insert(TreeNode* p,int h){   //每层的val按从左往右插入对应容器
            if(p==NULL) return; 
            res[h].push_back(p->val);     //插入
            insert(p->left,h+1);
            insert(p->right,h+1);
            return;
        }

        vector<vector<int> > Print(TreeNode* pRoot) {
            int h=0,t=1;//t用来先判断树的深度
            findt(pRoot,t);//判断深度递归
            res.resize(max);  //有多少层就定义几个小容器
            insert(pRoot,h);//递归插入
            return res;
        }
    
};

全部评论

相关推荐

榕城小榕树:1200单休,我去干点啥别的不好
点赞 评论 收藏
分享
06-28 22:48
已编辑
广东金融学院 Java
小浪_Coding:学院本+这俩项目不是buff叠满了嘛
点赞 评论 收藏
分享
仁者伍敌:难怪小公司那么挑剔,让你们这些大佬把位置拿了
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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