题目描述
一棵树有n个节点,其中1号节点为根节点。
输入格式
第一行是整数n,表示节点数
后面若干行,每行两个整数a b,表示b是a的子节点。
输出
求这棵树的高度(根节点为第1层)
样例输入
5
1 2
1 3
3 4
3 5
样例输出
一棵树有n个节点,其中1号节点为根节点。
输入格式
第一行是整数n,表示节点数
后面若干行,每行两个整数a b,表示b是a的子节点。
输出
求这棵树的高度(根节点为第1层)
样例输入
5
1 2
1 3
3 4
3 5
样例输出
3
#include<iostream>
using namespace std;
struct Node
{
int data;
Node *left;
Node *right;
};
int left_height = 0;
int right_height = 0;
Node *Tree_Insert(Node *T, int parent, int child)
{
Node *temp1 = T, *temp2;
if(temp1 == NULL)
return T;
//
if(temp1->data == parent)
{
temp2 = new Node;
temp2->data = child;
temp2->left = NULL;
temp2->right = NULL;
if(temp1->left == NULL)
{
temp1->left = temp2;
}
else
{
temp1->right = temp2;
}
return T;
}
Tree_Insert(T->left, parent, child);
Tree_Insert(T->right, parent, child);
return T;
}
int leftheight = 0;
int rightheight = 0;
int Tree_CengNum(Node *T)
{
if(T == NULL)
return 0;
if(T->left)
{
leftheight++;
Tree_CengNum(T->left) + 1;
}
if(T->right)
{
rightheight++;
Tree_CengNum(T->left) + 1;
}
return (leftheight > rightheight) ? (leftheight + 1) : (rightheight);
}
Node *Creat()
{
int n;
Node *T = NULL;
cin>>n;
while(n > 1)
{
int a, b;
cin>>a>>b;
T = new Node;
T->data = a;
T->left = NULL;
T->right = NULL;
T = Tree_Insert(T, a, b);
//
n--;
}
return T;
}
void main()
{
Node *T = Creat();
cout<<Tree_CengNum(T) + 1 <<endl;
system("pause");
}