二叉树的后序遍历非递归算法之c++实现

王朝c/c++·作者佚名  2006-01-10
宽屏版  字体: |||超大  

#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<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)

}

 
 
 
免责声明:本文为网络用户发布,其观点仅代表作者个人观点,与本站无关,本站仅提供信息存储服务。文中陈述内容未经本站证实,其真实性、完整性、及时性本站不作任何保证或承诺,请读者仅作参考,并请自行核实相关内容。
© 2005- 王朝网络 版权所有