//后序:
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)
}
//二叉树节点定义 class TreeNodeElement { public: TreeNodeElement();
TreeNodeElement(int value);
TreeNodeElement(int value,TreeNodeElement* l,TreeNodeElement* r);
~TreeNodeElement();
private: public: int _value;
TreeNodeElement* _l;
TreeNodeElement* _r; };
typedef TreeNodeElement* TreeNode; |
//递归实现(visit) void Visit(TreeNode node) { cout<<node->_value<<" "; } |
二叉树中序遍历的递归和非递归实现:
//递归遍历 void BinRetriveATree(TreeNode root,void (* visit)(TreeNode)) { if (root) { BinRetriveATree(root->_l,visit); (*visit)(root); BinRetriveATree(root->_r,visit); }
} |
//非递归遍历,添加#include <stack> void BinRetriveATreeWithoutRecurve(TreeNode root,void (* visit)(TreeNode)) { stack<TreeNode> tree;
while ((root != NULL) || (!tree.empty())) { while (root != NULL) { tree.push(root);
root = root->_l; }
if (!tree.empty()) { root = tree.top();
tree.pop();
visit(root);
root = root->_r; //转到右子树
} } } |
二叉树后序遍历的递归和非递归实现:
//递归遍历 void PostRetriveATree(TreeNode root,void (* visit)(TreeNode)) { if (root) { PostRetriveATree(root->_l,visit); PostRetriveATree(root->_r,visit); (*visit)(root); } } |
//非递归遍历,添加#include <stack> void PostRetriveATreeWithoutRecurve(TreeNode root,void (* visit)(TreeNode)) { stack<TreeNode> tree;
while ((root != NULL) || (!tree.empty())) { while (root != NULL) { tree.push(root);
root = root->_l; }
if (!tree.empty()) { root = tree.top();
if (root->_tag) //可以访问 { visit(root);
tree.pop();
root = NULL; //第二次访问标志其右子树也已经遍历 } else { root->_tag = true; root = root->_r; } } } } |