6-1 二叉树的深度* (10 分)

已知二叉树的结点结构定义如下:

typedef struct  NODE
{
    int data;
    struct  NODE  *lch, *rch;
} NODE;

说明:data 为数据域。lch 和 rch 分别为指示左、右孩子的指针。

请编写函数,求二叉树的深度。

函数原型

int Depth(const NODE *root);

说明:root 为二叉树的根指针,函数值为二叉树的深度。

裁判程序

int main()
{
    NODE *root;
    Create(&root);
    Input(&root);
    printf("%d\n", Depth(root));
    printf("%d\n", Depth(root));
    Destroy(&root);
    return 0;
}

说明:Create 函数创建空二叉树,Destroy 函数销毁二叉树。Input 函数按先根遍历顺序输入二叉树,结点值均为正整数,遇到空树时,输入零。

输入样例

85 37 94 53 0 0 21 0 0 0 18 46 0 60 0 0 9 0 72 0 0

输出样例

4
4


 


int Depth(const NODE *root)
{
    int dep1, dep2;
    if (root == NULL)
        return 0;
    else
    {
        dep1 = Depth(root->lch);//递归调用左子树
        dep2 = Depth(root->rch);//递归调用右子树
        return dep1 > dep2 ? dep1 + 1 : dep2 + 1;
        //返回两者中最大的值
    }
}

猜你喜欢

转载自blog.csdn.net/L5494326/article/details/121778745