6.44 编写递归算法:求二叉树中以元素值为x的结点为根的子树的深度

#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);

}
  • 7
    点赞
  • 50
    收藏
    觉得还不错? 一键收藏
  • 7
    评论
评论 7
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值