zoukankan      html  css  js  c++  java
  • 剑指offer---按只字形顺序打印二叉树

    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;
    
        }
    
    };
  • 相关阅读:
    MySQL开发规范与使用技巧总结
    Anaconda3(在D盘)安装jieba库具体步骤
    Python的reshape的用法
    oom和cpu负载的定位
    接口安全设计
    恍然间
    java原子类
    设计模式
    微服务
    常见的代码优化
  • 原文地址:https://www.cnblogs.com/159269lzm/p/7271741.html
Copyright © 2011-2022 走看看