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

按之字形顺序打印二叉树

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 <vector>
class Solution {
public:
    vector<vector<int> > Print(TreeNode* pRoot) {
        stack<TreeNode*> input;

        vector<vector<int>> ret;
        if(pRoot==nullptr)
            return ret;
        
        input.push(pRoot);
        int depth=1;
        while(!input.empty()){
            vector<int> psh;
            queue<TreeNode *> ptrpsh;

            //process middle
            while(!input.empty()){
                TreeNode * cur=input.top();
                psh.push_back(cur->val);
                ptrpsh.push(cur);
                input.pop();
            }

            //process next and push
            ret.push_back(psh);

            while(!ptrpsh.empty()){
                TreeNode * cur=ptrpsh.front();
                if(depth%2==1){
                    //left to right
                    
                    if(cur->left!=nullptr){
                        input.push(cur->left);
                    }
                    if(cur->right!=nullptr){
                        input.push(cur->right);
                    }
                }
                else{
                    if(cur->right!=nullptr){
                        input.push(cur->right);
                    }
                    if(cur->left!=nullptr){
                        input.push(cur->left);
                    }
                }
                ptrpsh.pop();
            }
            depth++;

        }
        //init ret and stack
        //when the stack
        //push to a ret .scan the ret,add the subnodes into the stack in specific ways.
        //continue,untill there is nothing can be add to the stack,quit

        return ret;
    }
    
};

//首先想到了栈

//主要卡在,出栈时,怎么同时存储子树

//其次,不同层次,先入左还是先入右有区别,使用标记来记录层次

//第三,储存的是指针,用于访问左右子树

//第四,每次循环处理一段,大循环处理多段

全部评论

相关推荐

notbeentak...:孩子,说实话,选择很重要,可能你换一个方向会好很多,但是现在时间不太够了,除非准备春招
点赞 评论 收藏
分享
10-22 15:25
门头沟学院 C++
种花网友小松:求求你别发了,我几乎都快嫉妒得疯了,倒在床上蒙住被子就开始抱着枕头尖叫流泪,嘴里一边喊着卧槽卧槽,一边又忍着,我边发边哭,打字的手都是抖的,后来我的手抖得越来越厉害,从心头涌起的思想、情怀和梦想,这份歆羡和悔恨交织在一起,我的笑还挂在脸上,可是眼泪一下子就掉下来了。求你了别发了,我生活再难再穷我都不会觉得难过,只有你们发这种东西的时候,我的心里像被刀割一样的痛,打着字泪水就忍不住的往下流。
我的求职进度条
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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