王道5-3-2-3非递归后续遍历


题目大意

给定一个二叉树,返回它的 后序 遍历。

示例:

输入: [1,null,2,3] 1 \ 2 / 3

输出: [3,2,1] 进阶: 递归算法很简单,你可以通过迭代算法完成吗?

来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/binary-

2.思路

构建模板

while( 栈非空 || p 非空)
{
if( p 非空)
{

}
else
{

}
}

填写步骤

  1. p非空一直左压
  2. 然后,如果是空的,获取栈的顶端,如果右节点也是空的或者访问了的就是p.right=pre,那么就直接访问当前的,并把p给pop出来,同时设置pre=p,标志访问,*同时设置p=null(否则下一次p会进入if判断,然后一直压)*
  3. 如果不是空的,并且没有访问,那么把p=p.right,他就会进入之前的if,一直左压

代码实现

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
   vector<int> postorderTraversal(TreeNode* root) {
    stack<TreeNode*> stack1;
    vector<int> vector;
//    两个一个判断,一个向前走
    TreeNode *p=root;
    TreeNode *pre= nullptr;
    while (p||!stack1.empty()){
        if (p){
//            如果p存在就一直左压
            stack1.push(p);
            p=p->left;
        } else{
//            不存在先取top
            p=stack1.top();
            if (!p->right||p->right==pre){
//                不存在,或者是之前访问的了
                vector.push_back(p->val);
//                并设置这个也是访问的
                pre=p;
//                弹出当前的
                stack1.pop();
                p= nullptr;

            } else{
//                设置为右边的,然后他访问右边的所有左树
                p=p->right;
            }
        }
    }
    return vector;
}
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
1.先序遍历非递归算法#define maxsize 100typedef struct{ Bitree Elem[maxsize]; int top;}SqStack;void PreOrderUnrec(Bitree t){ SqStack s; StackInit(s); p=t; while (p!=null || !StackEmpty(s)) { while (p!=null) //遍历左子树 { visite(p->data); push(s,p); p=p->lchild; }//endwhile if (!StackEmpty(s)) //通过下一次循环中的内嵌while实现右子树遍历 { p=pop(s); p=p->rchild; }//endif }//endwhile }//PreOrderUnrec2.中序遍历非递归算法#define maxsize 100typedef struct{ Bitree Elem[maxsize]; int top;}SqStack;void InOrderUnrec(Bitree t){ SqStack s; StackInit(s); p=t; while (p!=null || !StackEmpty(s)) { while (p!=null) //遍历左子树 { push(s,p); p=p->lchild; }//endwhile if (!StackEmpty(s)) { p=pop(s); visite(p->data); //访问根结点 p=p->rchild; //通过下一次循环实现右子树遍历 }//endif }//endwhile}//InOrderUnrec3.后序遍历非递归算法#define maxsize 100typedef enum{L,R} tagtype;typedef struct { Bitree ptr; tagtype tag;}stacknode;typedef struct{ stacknode Elem[maxsize]; int top;}SqStack;void PostOrderUnrec(Bitree t){ SqStack s; stacknode x; StackInit(s); p=t; do { while (p!=null) //遍历左子树 { x.ptr = p; x.tag = L; //标记为左子树 push(s,x); p=p->lchild; } while (!StackEmpty(s) && s.Elem[s.top].tag==R) { x = pop(s); p = x.ptr; visite(p->data); //tag为R,表示右子树访问完毕,故访问根结点 } if (!StackEmpty(s)) { s.Elem[s.top].tag =R; //遍历右子树 p=s.Elem[s.top].ptr->rchild; } }while (!StackEmpty(s));}//PostOrderUnrec
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值