c++双栈实现,时间复杂度O(n)

按之字形顺序打印二叉树

http://www.nowcoder.com/questionTerminal/91b69814117f4e8097390d107d2efbe0

class Solution {
public:
    vector<vector<int> > Print(TreeNode* pRoot) {
        vector<vector<int> > result;
        if(!pRoot) return result;
        int level=1,count=1;
        stack<TreeNode*> stk1, stk2;
        stk1.push(pRoot);
        while(!stk1.empty() || !stk2.empty())
        {
            vector<int> array;
            int i=count;
            count=0;
            while(i--)
            {
                if(level&1)
                {
                    array.push_back(stk1.top()->val);
                    if(stk1.top()->left) 
                    {
                        stk2.push(stk1.top()->left);
                        ++count;
                    }
                    if(stk1.top()->right) 
                    {
                        stk2.push(stk1.top()->right);
                        ++count;
                    }
                    stk1.pop();
                }
                else
                {
                    array.push_back(stk2.top()->val);
                    if(stk2.top()->right)
                    {
                        stk1.push(stk2.top()->right);
                        ++count;
                    }
                    if(stk2.top()->left)
                    {
                        stk1.push(stk2.top()->left);
                        ++count;
                    }
                    stk2.pop();
                }
            }
            result.push_back(array);
            ++level;
        }
        return result;
    }
};

全部评论

相关推荐

但听说转正率很低,我现在有在实习了,好纠结要不要去
熬夜脱发码农:转正率低归低,但是实习的经历你可以拿着,又不是说秋招不准备了
点赞 评论 收藏
分享
uu们,拒offer时hr很生气怎么办我哭死
爱睡觉的冰箱哥:人家回收你的offer,或者oc后没给你发offer的时候可不会愧疚你,所以你拒了也没必要愧疚他。
点赞 评论 收藏
分享
湫湫湫不会java:先投着吧,大概率找不到实习,没实习的时候再加个项目,然后把个人评价和荣誉奖项删了,赶紧成为八股战神吧,没实习没学历,秋招机会估计不多,把握机会。或者说秋招时间去冲实习,春招冲offer,但是压力会比较大
点赞 评论 收藏
分享
每晚夜里独自颤抖:这个在牛客不是老熟人了吗
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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