计算二叉树层次

输入:5(行)

           0 1 

          0   2

          1 2 

          1 3 

           3  4


输出        3 ( 层)

代码:

#include<stdio.h>
#include<stdlib.h>


typedef struct _tree
{
int data;
struct _tree * left;
struct _tree* right;
}tree;


tree * SearchTree(tree *node, int key)
{
tree *p = NULL;
if(node == NULL) return NULL;
if(node->data == key) return node;  
else 
{


p = SearchTree(node->left ,key);
if(p == NULL)
{
p = SearchTree(node->right ,key);
return p;
}
}
}




tree * InsertTree(tree * head, int root,int child)
{
if(head == NULL)
{
(head) = (tree * )malloc(sizeof(tree));
(head)->data = root;
(head)->left = NULL;
(head)->right = NULL;
}
tree * p = SearchTree(head,root);
printf("data = %d\n",p->data);


if(p != NULL)
{
tree * node = (tree *)malloc(sizeof(tree));
node->data = child;
node->left = NULL;
node->right = NULL;
if(p->left == NULL)
{
p->left = node;
}
else 
{
p->right = node;
}
}
return head;
}
int GetHigh(tree * root)
{
int l = 0 ;
int r = 0 ;
if(root == NULL) return 0;
else
{
l = GetHigh(root->left) +1;
r = GetHigh(root->right) +1;
int result =  l>r?l:r;
return result ;
}
}
int main()
{
int n;
scanf("%d",&n);
int i;
int root,child;
tree *head = NULL;
for(i = 0;i<n;i++)
{
scanf("%d %d",&root,&child);
head = InsertTree(head,root,child);
}
int result = GetHigh(head);
printf("result = %d\n",result);
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值