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

全部评论

相关推荐

点赞 收藏 评论
分享
牛客网
牛客企业服务