1.遍历
如二叉树:a+b*(c-d)-e/f
-
+ /
a * e f
b -
c d
先序:-+a*b-cd/ef
中序:a+b*c-d-e/f
后序:abcd-*+ef/-
层序:-+/a*efb-cd
1.1 先序遍历:递归/非递归
递归:
void PreOrder(BiNode<T> *root)
{
if(root==NULL) return;
else{
cout<<root->data<<" ";
PreOrder(root->lchild);
PreOrder(root->rchild);
}
}
非递归
template<class T>
void BiTree<T>::PreOrder2(BiNode<T> *root)
{
/*
push x:
stack[pop++]=x;
pop x:
x=stack[--pop];
*/
const int MaxSize = 100; //假定不会发生上溢
int pop = 0;
BiNode<T>* stack[MaxSize];
while(root!=NULL||pop!=0)
{
while(root!=NULL)
{
cout<<root->data<<" ";
stack[pop++]=root;
root=root->lchild;
}
if(pop!=0)
{
root=stack[--pop];
root=root->rchild;
}
}
}
1.2中序遍历:递归/非递归
void InOrder(BiNode<T> *root)
{
if (root==NULL) return; //递归调用的结束条件
else{
InOrder(root->lchild); //中序递归遍历root的左子树
cout<<root->data<<" "; //访问根结点的数据域
InOrder(root->rchild); //中序递归遍历root的右子树
}
}
非递归:
template <class T>
void BiTree<T>::InOrder2 (BiNode<T> *root)
{
const int MaxSize = 100; //假定不会发生上溢
int pop = 0;
BiNode<T>* stack[MaxSize];
while(root!=NULL||pop!=0)
{
while(root!=NULL)
{
stack[pop++]=root;
root=root->lchild;
}
if(pop!=0)
{
root=stack[--pop];
cout<<root->data<<" ";
root=root->rchild;
}
}
}
1.3后序遍历:
template <class T>
void BiTree<T>::PostOrder(BiNode<T> *root)
{
if (root==NULL) return; //递归调用的结束条件
else{
PostOrder(root->lchild); //后序递归遍历root的左子树
PostOrder(root->rchild); //后序递归遍历root的右子树
cout<<root->data<<" "; //访问根结点的数据域
}
}
非递归:
template <class T>
void BiTree<T>::PostOrder2(BiNode<T> *root)
{
const int MaxSize = 100; //假定不会发生上溢
int pop = 0;
element<T> stack[MaxSize];
while(root!=NULL||pop!=0)
{
while(root!=NULL)
{
pop++;
stack[pop-1].ptr=root;
stack[pop-1].flag=false;
root=root->lchild;
}
while(pop!=0&&stack[pop-1].flag==true)
{
root=stack[--pop].ptr;
cout<<root->data<<" ";
root=NULL;
}
if(pop!=0)
{
stack[pop-1].flag=true;
root= stack[pop-1].ptr->rchild;
}
}
}
1.4层序遍历
template <class T>
void BiTree<T>::LeverOrder(BiNode<T> *root)
{
const int MaxSize = 100;
int front = 0;
int rear = 0; //采用顺序队列,并假定不会发生上溢
BiNode<T>* Q[MaxSize];
BiNode<T>* q;
if (root==NULL) return;
else{
Q[rear++] = root;
while (front != rear)
{
q = Q[front++];
cout<<q->data<<" ";
if (q->lchild != NULL) Q[rear++] = q->lchild;
if (q->rchild != NULL) Q[rear++] = q->rchild;
}
}
}