求二叉树的直径

#include<stdio.h>
#include<stdlib.h>
typedef int status;
typedef struct BiTNode
{
	int data,new_data;
	struct BiTNode* lchild, *rchild;
}BiTNode, *BiTree;

BiTree creat()
{
    BiTree root = (BiTree)malloc(sizeof(BiTNode));
    int x;
    scanf("%d", &x);
    if(x==-1)
        root = NULL;
    else
    {
        root->data = x;
        root->lchild = creat();
        root->rchild = creat();
    }
    return root;
}

//树的最大直径,应该是左子树的高度加上右子树的高度叭

int depth(BiTree bt)
{
    if(bt==NULL)    return 0;
    else
    {
        int left=1+depth(bt->lchild);
        int right=1+depth(bt->rchild);
        return (left>right?left:right);
    }
}


int main()
{
    BiTree bt=creat();
    int diameter = depth(bt->lchild)+depth(bt->rchild);
    
    printf("%d",diameter);
    
    return 0;
}
发布了98 篇原创文章 · 获赞 9 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/qq_43661234/article/details/103326961
今日推荐