一、三种常用的遍历方式:先序、中序、后序
- 先序遍历操作过程(DLR)
(1)访问根结点
(2)按先序遍历左子树
(3)按先序遍历右子树
算法:
void PreOrder(BiTree root){
if(root != NULL){
Visit(root->data);
PreOrder(root->LChild);
PreOrder(root->RChild);
}
}
- 中序遍历操作过程(LDR)
(1)按中序遍历左子树
(2)访问根结点
(3)按中序遍历右子树
算法:
void InOrder(BiTree root){
if(root != NULL){
InOrder(root->LChild);
Visit(root->data);
InOrder(root->RChild);
}
}
- 后序遍历操作过程(LDR)
(1)按后序遍历左子树
(2)按后序遍历右子树
(3)访问根结点
算法:
void PostOrder(BiTree root){
if(root != NULL){
PostOrder(root->LChild);
PostOrder(root->RChild);
Visit(root->data);
}
}
二、二叉树遍历应用
(1)统计叶子结点数目(后序遍历)
int LeafCount=0;
void leaf(BiTree root){
if(root != null){
leaf(root->LChild);
leaf(root->Rchild);
if(root ->LChild == NULL && root->RChild==NULL) LeafCount++;
}
}
(2)先序遍历求二叉树的高度
void PreTreeDepth(BiTree bt ,int h){
if( bt !=NULL){
if(h>depth) depth=h;
PreTreeDepth(bt->LChild,h+1);
PreTreeDepth(bt->RChild,h+1);
}
}
(3)打印二叉树形状(后序)
void PrintTree(BiTree bt,int nLayer){
if(bt == NULL) return;
PrintTree(bt->RChild ,nLayer+1);
for(int i=0;i<nLayer;i++){
printf(" ");
}
printf("%c\n",bt->data);
PrintTree(bt->LChild,nLayer+1);
}