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

按之字形顺序打印二叉树

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,导致出错。

全部评论

相关推荐

做个有文化的流氓:不想当将军的士兵不是好士兵
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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