二叉树的后序遍历非递归算法之C++实现 选择自 xuyongfeng 的 Blog

这个是比较好理解的一个后序遍历非递归算法,可能是我学的是C++的缘故。另外有的算法里面有flag(或者tag),让人很头晕。。。
为了自己理解方便,添加了部分注释。

#include <stack>
#include <iostream>
using namespace std;

template <class T>
class TreeNode //定义节点类
{
  public:
    T data;
    TreeNode<T> *left; //left child
    TreeNode<T> *right; //right child
    //构造函数
    TreeNode():left(NULL),right(NULL)
    {
    }

    TreeNode(const T& t):data(t),left(NULL), right(NULL)
    {
    }

    TreeNode(const T& t, TreeNode<T*> left, TreeNode<T*> right):data(t),left(left), right(left)
    {
    }
};

/*purpose: 对二叉树进行后序遍历(非递归算法)
  *@param TreeNode<T> *root the root of the binary tree

*/
template <class T>
void postOrder(TreeNode<T> *root)
{
  stack<TreeNode<T>*> st;//定义栈,节点类型为TreeNode
  TreeNode<T> *p = root;
  TreeNode<T> *pre = NULL;//pre表示最近一次访问的结点
 
  while(p || st.size()!=0)
  {
    //沿着左孩子方向走到最左下 。
    while(p)
    {
      st.push(p);
      p = p->left;
    }
    //get the top element of the stack
    p = st.top();
    //如果p没有右孩子或者其右孩子刚刚被访问过
   if(p->right == NULL || p->right == pre)
    {
      //visit this element and then pop it
      cout << "visit: " << p->data << endl;
      st.pop();
      pre = p;
      p = NULL;    
    }
   else
   {
     p = p->right; 
   }
  }//end of while(p || st.size()!=0)

}

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 3
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值