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

把二叉树打印成多行

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

参考模版:
BFS是很经典的模板,模板在手,天下我有。
模板的精髓
1.使用队列来确保每层的先后顺序不发生变化
2.遍历的时候取出队列的size,确保每次只遍历一层。

/*
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) {
            vector<vector<int> > res;
            queue<TreeNode*> p;
            if(pRoot){
                p.push(pRoot);
            }
            while(!p.empty()){
                int size = p.size();
                vector<int> current = {};
                while(size--){
                    TreeNode *node = p.front();
                    p.pop();
                    current.push_back(node->val);
                    if(node->left){
                        p.push(node->left);
                    }
                    if(node->right){
                        p.push(node->right);
                    }
                }
                res.push_back(current);
            }
            
            return res;
        }
    
};

全部评论

相关推荐

10-13 13:49
南京大学 财务
饿魔:笑死我了,你简直是个天才
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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