首页 > 其他 > 详细

二叉树-专题

时间:2017-08-06 20:22:53      阅读:179      评论:0      收藏:0      [点我收藏+]

题型一:非递归遍历二叉树后续

struct node
 {
    bool isfirst;
    int val;
    TreeNode* left,*right;
    node(int _val,bool _isfirst){
        val=_val;
        isfirst=_isfirst;
        this->left=this->right=NULL;
    }
 };

vector<int> postorderTraversal(TreeNode *root) {
        // write your code here
        vector<int> ret;
        stack<node> sta;
        TreeNode* p=root;
        while(sta.size()>0||p)
        {
            while(p)
            {
                node n1(p->val,false);
                n1.left=p->left;
                n1.right=p->right;
                sta.push(n1);
                p=p->left;
            }
            if(sta.size()>0)
            {
                node tmp=sta.top();
                sta.pop();
                if(tmp.isfirst==false)
                {
                    tmp.isfirst=true;
                    sta.push(tmp);
                    p=tmp.right;
                }
                else
                {
                    ret.push_back(tmp.val);
                    p=NULL;
                }
            }
        }
        return ret;
    }

  题型二:非递归二叉序前序遍历(中序差不多,就不写了,自己去脑补去。。。。

vector<int> preorderTraversal(TreeNode *root) {
        // write your code here
        vector<int> ret;
        stack<TreeNode*> sta;
        TreeNode* p=root;
        while(sta.size()>0||p)
        {
            while(p)
            {
                sta.push(p);
                ret.push_back(p->val);
                p=p->left;
            }
            if(sta.size())
            {
                TreeNode* tmp=sta.top();
                sta.pop();
                p=tmp->right;
            }
        }
        return ret;
    }

  

二叉树-专题

原文:http://www.cnblogs.com/wuxiangli/p/7295576.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!