#include <stdio.h>
#include <malloc.h>
typedef struct BTNode {
int data;
struct BTNode *left, *right;
}BTNode;
BTNode *creat_bt(){ //按扩展前序建二叉树;
BTNode *t;int x;
scanf("%d",&x);
if (x==0) t=NULL;
else
{ t=(BTNode *)malloc(sizeof(BTNode));
t->data=x;
t->left=creat_bt();
t->right=creat_bt();
}
return t;
}
//先以先序遍历递归找到元素值为x的结点,然后再递归求以x为根结点的子树的深度
BTNode *preorder_x(BTNode *bt, int x)
{
if (bt != NULL){
if (bt->data==x)
return bt;
BTNode *t=NULL;
t=preorder_x(bt->left, x);
if(t) return t;
t=preorder_x(bt->right, x);
if(t) return t;
}
return NULL;
}
int depth(BTNode *bt)
{
int h1=0,h2=0;
if (bt == NULL) return 0;
else if (bt->left == NULL && bt->right == NULL) return 1;
else{
h1 = depth(bt->left);
h2 = depth(bt->right);
return (h1>h2?h1:h2)+1;
}
}
int main()
{
BTNode *bt = creat_bt();
int x;
printf("请输入x的值:");
scanf("%d", &x);
BTNode *p = preorder_x(bt, x);
int d=depth(p);
printf("以元素值为x的结点为根的子树的深度为:%d", d);
}
6.44 编写递归算法:求二叉树中以元素值为x的结点为根的子树的深度
最新推荐文章于 2023-10-24 00:41:21 发布