递归求二叉树某一层的所有节点及求二叉树的高度
1、输出二叉树某一层上所有的节点,一般用递归方式解决。
2、求二叉树的高度,也用递归方式解决。
//求最大值
QQ20160316-2@2x.png//创建🌲
QQ20160316-3@2x.png打印二叉树某一层上的所有节点
QQ20160316-4@2x.png//打印🌲
QQ20160316-5@2x.png//求二叉树的高度
QQ20160316-6@2x.png//main函数:
QQ20160316-7@2x.png//控制台输出
QQ20160316-8@2x.png//相关代码
include <stdio.h>
include <string.h>
include <stdlib.h>
typedef struct bnode{
int value;
struct bnode *lchild;
struct bnode *rchild;
}btnode;
int max (int x, int y)
{
return x>y?x:y;
}
void createLR(btnode *pn)
{
if ((pn->value)<50) {
btnode *pl = (btnode *)malloc(sizeof(btnode));
btnode pr = (btnode )malloc(sizeof(btnode));
pl->value = (pn ->value)2;
pr->value = (pn->value)2+1;
pn->lchild = pl;
pn->rchild = pr;
createLR(pl);
createLR(pr);
}else{
pn->lchild = NULL;
pn->rchild = NULL;
}
}
//打印二叉树某一层上的所有节点
void level_sum_out(btnode *p,int level){
if (!p) {
return;
}
if (level == 1) {
printf("== %d",p->value);
}else{
level_sum_out(p->lchild,level-1);
level_sum_out(p->rchild,level-1);
}
}
void print(btnode *t){
if (t!=NULL) {
printf("%d ",t->value);
print(t->lchild);
print(t->rchild);
}
}
//二叉树的高度
int getHeight(btnode *t){
if (t==NULL) {
return 0;
}else{
return max(getHeight(t->lchild)+1, getHeight(t->rchild)+1);
}
}
int main(int argc, const char * argv[]) {
// insert code here...
int ans;
btnode *t = (btnode *)malloc(sizeof(btnode));
t->value =1;
createLR(t);
print(t);
printf("\n");
level_sum_out(t,5);
ans= getHeight(t);
printf("\n%d\n",ans);
return 0;
}