二叉树的顺序存储:
使用一组连续的存储单元存储二叉树的数据元素。
使用节点之间的相对位置表示节点之间的关系。
由上图可知,顺序存储方式适用于完全二叉树。
二叉树的遍历:
DLR:先(根)序遍历算法
void PreOrder(BiTree root){
if(root!=NULL){
visit(root->data); //printf("%c",root->data);
PreOrder(root->lchild);
PreOrder(root->rchild);
}
}
LDR:中(根)序遍历算法
void InOrder(BiTree root){
if(root!=NULL){
InOrder(root->lchild);
visit(root->data); //printf("%c",root->data);
InOrder(root->rchild);
}
}
LRD:后(根)序遍历算法
void PostOrder(BiTree root){
if(root!=NULL){
PostOrder(root->lchild);
PostOrder(root->rchild);
visit(root->data); //printf("%c",root->data);
}
}
二叉树统计叶子节点的个数:
//根据遍历法求解
int LeafCount=0;
void LeafNum(BiTree root){
if(root->lchild==NULL&&root->rchild==NULL){
LeafCount++;
}
LeafNum(root->lchild);
LeafNum(root->rchild)l
}
//分治法求解
int leaf(BiTree root){
int LeafCount;
if(root==NULL){
LeafCount=0;
}
else if(root->lchild==NULL&&root->rchild==NULL){
LeafCount=1;
}
else
LeafCount=leaf(root->lchild)+leaf(root->rchild);
return LeafCount;
}
求二叉树的高度:
//遍历算法
int PostTreeDepth(BiTree root){
int hl,hr,max;
if(root!==NULL){
hl=PostTreeDepth(root->lchild);
hr=PostTreeDepth(root->rchild);
max=hl>hr?hl:hr;
return max+1;
}
else
return 0;
}
//层次的思想
int Depth=0;
int PostTreeDepth(BiTree root,int h){
if(h>Depth)
Depth=h;
PostTreeDepth(root->lchild,h+1);
PostTreeDepth(root->rchild,h+1);
}