基于二叉树的算法
1.统计二叉树中度为1的节点个数
int NodeCount(BiTree bt){
if(bt == null) return 0;
if(bt->lchild == null && bt->rchild != null || bt->lchild != null && bt->rchild == null)
return 1+NodeCount(bt->lchild) + NodeCount(bt->rchild);
return NodeCount(bt->lchild) + NodeCount(bt->rchild);
}
2.统计二叉树中度为2的节点个数
int NodeCount(BiTree bt){
if(bt == null) return 0;
if(bt->lchild != null && bt->rchild != null)
return 1+NodeCount(bt->lchild) + NodeCount(bt->rchild);
}
3.统计二叉树中度为0的节点个数(叶节点)
int NodeCount(BiTree bt){
if(bt == null) return 0;
if(bt->lchild == null && bt->rchild == null)
return 1;
else
return NodeCount(bt->lchild) + NodeCount(bt->rchild);
}
4.计算二叉树高度
int height(BiTree bt){
if(bt == null) return 0;
int LHeight = height(bt->left);
int RHeight = height(bt->right);
return (LHeight > RHeight ? LHeight : RHeight) + 1;
}
5.计算二叉树最大高度(基于先序遍历)
int count[MaxSize];
int max = -1;
void width(BiTree bt, int k){
if(bt == null) return;
count[k]++; //该层节点数+1
if(max<count[k]) max = count[k];
width(bt->lchikd, k+1);
width(bt->rchild, k+1);
}
6.删除二叉树中所有叶节点
void Del_0(BiTree bt){
BiTree *p = bt;
if((p->lchild == null && p->rchild == null) || p == null)
free(p);
return;
if(p->lchild->lchild == null && p->lchild->rchild == null)
free(p->lchild); //说明是叶节点,删掉
p->lchild = null;
else(p->rchild->lchild == null && p->rchild->rchild == null)
free(p->rchild);
p-rchild = null;
Del_0(p->lchild);
Del_0(p->rchild);
}
7.计算二叉树指定节点所在层次
int level(BiTree bt, BiTree *p){
int d1,d2;
if(bt == null) return 0;
if(bt == p) return 1;
d1 = level(bt->lchild, p);
d2 = level(bt->rchild, p);
if(d1 || d2) return 1+(d1>d2 ? d1:d2);
retrun 0;
}
8.交换二叉树左右子树
void swap(BiTree bt){
if(bt){
swap(bt->lchild);
swap(bt->rchild);
BiTree *temp = bt->lchild;
bt->lchild = bt->rchild;
bt->rchild = temp;
}
}
9.后序遍历非递归算法
void PostOrder(BiTree T){
InitStack(S);
BiTree *p = T;
BiTree *r = null;
while(p || !IsEmpty(S)){
if(p){
Push(S,p);
p = p->lchild;
}else{
GetTop(S,p);
if(p->rchild && p->rchild != r){ //判断是否有右子树
p = p->rchild;
}else{
Pop(S,p);
visit(p->data);
r = p;
p = null;
}
}
}
}
作者:Jace Jin
github地址:https://github.com/buxianghua
原创文章版权归作者所有.
欢迎转载,转载时请在文章页面明显位置给出原文连接,否则保留追究法律责任的权利.
欢迎转载,转载时请在文章页面明显位置给出原文连接,否则保留追究法律责任的权利.