看了很多的数据结构资料,很少看到有把实现后续遍历当成,二叉树遍历的例子来讲解的,大都采用中序遍历作为例子;相比而言,实现二叉树的后续遍历就稍微麻烦一些,但是这更能启发思考,所以,将我自己的一种实现作为参考提供给大家;正确性还有待验证,本人验证的事例无误。希望发现问题的能给指正。
闲话不多说了!请看代码:
二叉树后续遍历:
template<class T> class TreeNode
{
public:
TreeNode(T d=0)
{
data=d;
rightchild=leftchild=0;
};
private:
TreeNode<T> *leftchild,*rightchild;
T data;
};
template<class T>
void Tree<T>::MypostOrder()
{
if (!root) {cout<<"the tree is null;";return ;}
MypostOrder(root);
}
template<class T>
void Tree<T>::MypostOrder(TreeNode<T>*root)
{
stack<TreeNode<T>*> s;
TreeNode<T>*currentnode=root;
while (1)
{
while (currentnode)
{
s.push(currentnode);
/*一直向左子移动,若无左子则向右子移动*/
currentnode=currentnode->leftchild?currentnode->leftchild:currentnode->rightchild;
}
//此时栈顶元素左,右子皆为NULL
if(s.empty()) return;
currentnode=s.top();
s.pop();
cout<<currentnode->data<<" ";//访问叶子节点,(vist)
//此时栈顶元素肯定是该结点的父节点
//走向未被访问的父节点的右子,若右子已被访问,则访问该父节点
TreeNode<T>* temp=currentnode;//刚刚被访问的点
do
{
if (s.empty())
return;
currentnode=s.top();
if (temp==currentnode->rightchild)
{
cout<<currentnode->data<<" ";//访问左、右子节点皆已被访问的节点 (后续访问)
s.pop();
temp=currentnode;
}
else
{
currentnode=currentnode->rightchild;//向右子移动
break;
}
} while (1);
}
}

本文深入探讨了二叉树后续遍历的实现过程,通过具体代码实例展示了如何利用栈来完成这一复杂操作,强调了理解二叉树结构及遍历算法的重要性。
1283

被折叠的 条评论
为什么被折叠?



