码迷,mamicode.com
首页 > 其他好文 > 详细

剑指offer---按只字形顺序打印二叉树

时间:2017-08-02 10:01:18      阅读:99      评论:0      收藏:0      [点我收藏+]

标签:else   tor   tac   roo   剑指offer   nbsp   treenode   null   pre   

class Solution 
{
public:
    vector<vector<int> > Print(TreeNode* pRoot) 
    {
        
        TreeNode* cur = pRoot;
        stack<TreeNode*> stack1_LeftToRight;
        stack<TreeNode*> stack2_RightToLeft;
        stack1_LeftToRight.push(pRoot);
        vector<vector<int> > result;
        if (pRoot == NULL)    return result;
        while ((!stack1_LeftToRight.empty()) || (!stack2_RightToLeft.empty()))
        {
            vector<int> re;
            if( (!stack1_LeftToRight.empty()) && (stack2_RightToLeft.empty()))
            {
                while (!stack1_LeftToRight.empty())
                {
                    TreeNode* cur= stack1_LeftToRight.top();
                    if(cur->left!=NULL) stack2_RightToLeft.push(cur->left);
                    if(cur->right!=NULL) stack2_RightToLeft.push(cur->right);
                    re.push_back(cur->val);
                    stack1_LeftToRight.pop();
                }
                result.push_back(re);
            }
            else
            {
                while (!stack2_RightToLeft.empty())
                {
                    TreeNode* cur = stack2_RightToLeft.top();
                    if(cur->right!=NULL) stack1_LeftToRight.push(cur->right);
                    if(cur->left!=NULL) stack1_LeftToRight.push(cur->left);
                    re.push_back(cur->val);
                    stack2_RightToLeft.pop();
                }
                result.push_back(re);    
            }
            re.clear();
        }
        return result;

    }

};

 

剑指offer---按只字形顺序打印二叉树

标签:else   tor   tac   roo   剑指offer   nbsp   treenode   null   pre   

原文地址:http://www.cnblogs.com/159269lzm/p/7271741.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!