题解 | #按之字形顺序打印二叉树#

按之字形顺序打印二叉树

https://www.nowcoder.com/practice/91b69814117f4e8097390d107d2efbe0

/*
struct TreeNode {
    int val;
    struct TreeNode *left;
    struct TreeNode *right;
    TreeNode(int x) :
            val(x), left(NULL), right(NULL) {
    }
};
*/
#include <cstddef>
class Solution {
public:
    vector<vector<int> > Print(TreeNode* pRoot) {
        vector<vector<int>> res;
        queue<TreeNode *> q;
        if(!pRoot) return res;
        int count = 0;
        q.push(pRoot);
        while(!q.empty()){
            vector<int> ans;
            count ++;
            int size = q.size();
            for(int i = 0;i < size;i ++){
                cout << i << " ";
                if(q.front() -> left) q.push(q.front()->left);
                if(q.front() -> right) q.push(q.front()->right);
                if(count % 2 == 1){
                    ans.push_back(q.front() -> val);
                }
                else if(count % 2 == 0){
                    ans.insert(ans.begin(),q.front() -> val);
                }
                q.pop();
            }
            res.push_back(ans);
        }
        return res;
    }
    
};

重写这道题,发现把q.size()写到for里面去了,for里面又在操作q,导致出错。

全部评论

相关推荐

07-02 10:39
门头沟学院 Java
Steven267:说点真实的,都要秋招了,还没有实习,早干嘛去了,本来学历就差,现在知道急了,而且你这个简历完全可以写成一页,劣势太大了,建议转测试
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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