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

把二叉树打印成多行

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

1

一轮AC

  • 还是典型的bfs模板
  • 末尾总结下当前遇到的bfs 层次题目

2 code

/*
struct TreeNode {
    int val;
    struct TreeNode *left;
    struct TreeNode *right;
    TreeNode(int x) :
            val(x), left(NULL), right(NULL) {
    }
};
*/
class Solution {
public:
        vector<vector<int> > Print(TreeNode* pRoot) {
        //分行的bfs
            vector<vector<int> > outV;
            if(!pRoot){
                return outV;
            }
            
            queue<TreeNode *> q;
            q.push(pRoot);
            
            int sz =0;

            while( !q.empty()){
               sz = q.size();
                
                //inside;
                vector<int> innerV;
                //level control while(sz)
                while(sz--){
                    //get queue top
                    TreeNode * top = q.front();
                    innerV.push_back(top->val);
                    q.pop();
                    
                    //get child pushed
                    if(top->left){
                        q.push(top->left);
                    }
                    if(top->right){
                        q.push(top->right);
                    }
                    
                    
                }
                outV.push_back(innerV);
            }
            
            return outV;
            
        }
    
};

3 类似题目

JZ32 从上往下打印二叉树

来自 https://www.nowcoder.com/practice/7fe2212963db4790b57431d9ed259701?tpId=13&tqId=23280&ru=/exam/oj/ta&qru=/ta/coding-interviews/question-ranking&sourceUrl=%2Fexam%2Foj%2Fta%3FtpId%3D13

JZ78 把二叉树打印成多行

来自 https://www.nowcoder.com/practice/445c44d982d04483b04a54f298796288?tpId=13&tqId=23453&ru=/exam/oj/ta&qru=/ta/coding-interviews/question-ranking&sourceUrl=%2Fexam%2Foj%2Fta%3FtpId%3D13 JZ77 按之字形顺序打印二叉树

来自 https://www.nowcoder.com/practice/91b69814117f4e8097390d107d2efbe0?tpId=13&tqId=23454&ru=/exam/oj/ta&qru=/ta/coding-interviews/question-ranking&sourceUrl=%2Fexam%2Foj%2Fta%3FtpId%3D13

全部评论

相关推荐

11-01 08:48
门头沟学院 C++
伤心的候选人在吵架:佬你不要的,能不能拿户口本证明过户给我。。球球了
点赞 评论 收藏
分享
评论
点赞
收藏
分享
牛客网
牛客企业服务