1、前序遍历
void Preorder(BinaryTreeNode<T>* t)
{
Stack<BinaryTreeNode<T>*> s(10);
BinaryTreeNode<T>* p=t;
s.push(p);
while(!s.isEmpty())
{
p = s.pop();
cout<<p->element;
if(p->Right != null)
{
s.push(p->Right);
}
if(p->Left != null)
{
s.push(p->Left);
}
}
}
这是我目前为止看到的最简单的前序遍历代码。
2、中序遍历
void Inorder(BinaryTreeNode<T>* t)
{
Stack<BinaryTreeNode<T>*> s(10);
BinaryTreeNode<T>* p = t;
while(true)
{
while(p != null)
{
s.push(p);
p = p->Left;
}
if(!s.isEmpty())
{
p = s.pop();
cout<<p->element;
p = p->Right;
}else{
return;
}
}
}
3、后序遍历
struct StkNode{
BinaryTreeNode<T> *ptr;
int tag;//tag=0代表左子树未遍历,tag=1表示左子树已遍历
}
void Postorder(BinaryTreeNode<T>* t)
{
Stack<StkNode<T>> s(10);
StkNode<T> currentNode;
BinaryTreeNode<T>* p = t;
while(true)
{
while(p != null)
{
currentNode.ptr = p;
currentNode.tag = 0;
s.push(currentNode);
p = p.Left;
}
currentNode = s.pop();
p = currentNode.ptr;
while(currentNode.tag == 1)//当tag=0时表示左子树未遍历完,当tag=1时表示从右子树回来时可以输出节点了
{
cout<<p->element;
if(!s.isEmpty())
{
currentNode = s.pop();
p = currentNode.ptr;
}else{
return;
}
}
currentNode.tag = 1;//从左子树回来,将tag赋值为1
s.push(currentNode);//开始遍历右子树
p = p->Right;
}
}
后序遍历应该是四种遍历中最复杂的一个了。4、层序遍历
void Levelorder(BinaryTreeNode<T>* t)
{
Queue<BinaryTreeNode<T>*> q;
BinaryTreeNode<T>* p = t;
while(p != null)
{
cout<<p->element;
if(p->Left != null)
{
q.add(p->Left);
}
if(p->Right != null)
{
q.add(p->Right);
}
if(!q.isEmpty())
{
p = q.removeFirst();
}else{
return;
}
}
}
层序遍历是依赖队列实现的,其他三种遍历均需要依赖栈来实现。
这四种遍历一定要熟记于心,属于二叉树的最基本内容。