使用栈的二叉树前序与中序遍历
使用栈的前序与后序遍历比较简单,只不过改变输出位置。但是原理是要清楚的。
template<class T>
struct BiNode
{
T data;
BiNode<T>* lchild, *rchild;
};
template<class T>
void BiTree<T>::UnReCurPreOrder(BiNode<T>* bt)
{
printf("非递归前序遍历:");
if (nullptr == bt)
{
return;
}
stack<BiNode<T>*> SNode;
while (nullptr != bt || !SNode.empty())
{
while (nullptr != bt)
{
SNode.push(bt);//前序遍历在压榨时输出
cout << bt->data << " ";
bt = bt->lchild;
}
if (nullptr == bt)
{
bt = SNode.top()->rchild;
SNode.pop();
}
}
puts("");
}
template<class T>
void BiTree<T>::UnReCurInOrder(BiNode<T>* bt)
{
printf("非递归中序遍历:");
if (nullptr == bt)
{
return;
}
stack<BiNode<T>*> SNode;
while (nullptr != bt || !SNode.empty())
{
while (nullptr != bt)
{
SNode.push(bt);
bt = bt->lchild;
}
if (nullptr == bt)
{
bt = SNode.top();//中序遍历在弹栈时输出
cout << bt->data << " ";
SNode.pop();
bt = bt->rchild;
}
}
puts("");
}