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;
    }
};

全部评论

相关推荐

点赞 评论 收藏
分享
但听说转正率很低,我现在有在实习了,好纠结要不要去
熬夜脱发码农:转正率低归低,但是实习的经历你可以拿着,又不是说秋招不准备了
点赞 评论 收藏
分享
qq乃乃好喝到咩噗茶:院校后面加上211标签,放大加粗,招呼语也写上211
点赞 评论 收藏
分享
程序员牛肉:主要是因为小厂的资金本来就很吃紧,所以更喜欢有实习经历的同学。来了就能上手。 而大厂因为钱多,实习生一天三四百的就不算事。所以愿意培养你,在面试的时候也就不在乎你有没有实习(除非是同级别大厂的实习。) 按照你的简历来看,同质化太严重了。项目也很烂大街。 要么换项目,要么考研。 你现在选择工作的话,前景不是很好了。
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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