为什么断更了呢 正常下去每天晚上学会儿政治就要来更csdn了,但是...其实说来也是幸运 保研了... 那为什么又重新更了呢,因为实习面试的时候写一道用二叉树递归的算法半天没写对,给自己气坏了,于是打算把这个系列给更完,也希望得到各位看客们的认可、
递归函数最重要的就是弄清楚终止条件和什么时候嵌套调用,二叉树递归的终止条件是遇到空结点!!
一、二叉树求结点数、叶子结点数、求某元素的值
先序遍历+记录结点
int count=0;
int pre_order(BiTree T){
if(T!=NULL){
count++;
pre_order(T->left);
pre_order(T->right);
}
}
只需要将if语句添加在先序位置且满足要求即可。
二、树求高度、宽度
求高度
int get_depth(BiTree T){
if(T==NULL) return 0;
int l=get_depth(T->left);
int r=get_depth(T->left);
return 1+l>r?l:r;
}
求宽度
int record[100]={0};
void get_width(BiTree T,int k){
if(T==NULL) return ;
count[k]++;
}
int max=0;
for(int i=0;i<get_depth(T);i++){
if(count[i]>max) max=count[i];
}
三、判断是否为平衡二叉树
平衡二叉树的定义是左右子树的高度差不能为1,因此很适合用递归来写,当一个树是空树的时候,一定为平衡二叉树;否则,则判断这个树左右子树的高度差是否大于1;
bool is_ph(BiTree T){
if(T==NULL){
return true;
}
int left=get_depth(T->left);
int rigth=get_depth(T->right);
if(abs(left-right)>1) return false
else return is_ph(T->left)&&is_ph(T->right);
}