题目描述
现在有一棵合法的二叉树,树的节点都是用数字表示,现在给定这棵树上所有的父子关系,求这棵树的高度
输入描述:
输入的第一行表示节点的个数n(1 ≤ n ≤ 1000,节点的编号为0到n-1)组成, 下面是n-1行,每行有两个整数,第一个数表示父节点的编号,第二个数表示子节点的编号
输出描述:
输出树的高度,为一个整数
示例1
输入
5 0 1 0 2 1 3 1 4
输出
3
解法一:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
|
#include<iostream>
using
namespace
std;
class
Node{
int
data;
Node *leftChild;
Node *rightChild;
public
:
Node(){leftChild = rightChild = NULL;}
void
setLeft(
int
d){
leftChild =
new
Node();
leftChild->data = d;
}
void
setData(
int
d){
data = d;
}
int
getData(){
return
data;
}
Node *getLeftChild(){
return
leftChild;
}
Node *getRightChild(){
return
rightChild;
}
void
setRight(
int
d){
rightChild =
new
Node();
rightChild->data = d;
}
inline
bool
leftEmpty(){
return
leftChild == NULL;
}
inline
bool
rightEmpty(){
return
rightChild == NULL;
}
};
class
Tree{
Node *root;
void
del(Node *r){
if
(r == NULL)
return
;
del(root->getLeftChild());
del(root->getRightChild());
delete
r;
}
public
:
Tree(){root = NULL;}
void
connect(
const
int
&p,
const
int
&c){
if
(root == NULL){
root =
new
Node();
root -> setData(p);
root -> setLeft(c);
}
else
{
preOrder(root,p,c);
}
}
int
getHeight(){
return
height(root);
}
int
height(Node* r){
if
(r == NULL)
return
0;
if
(r->leftEmpty() && r->rightEmpty())
return
1;
int
left,right;
left = height(r->getLeftChild());
right = height(r->getRightChild());
return
(left>right?left:right)+1;
}
bool
preOrder(Node *r,
const
int
&p,
const
int
&c){
if
(r == NULL)
return
false
;
if
(r->getData() == p){
if
(r->leftEmpty()){
r->setLeft(c);
}
else
if
(r->rightEmpty()){
r->setRight(c);
}
else
return
false
;
return
true
;
}
if
(preOrder(r->getLeftChild(),p,c))
return
true
;
if
(preOrder(r->getRightChild(),p,c))
return
true
;
return
false
;
}
~Tree(){
if
(root != NULL)
delete
(root);
}
};
int
main(){
int
n;
int
num_parent,num_child;
Tree tree;
cin>>n;
for
(
int
i = 0;i < n-1;++i){
cin>>num_parent>>num_child;
tree.connect(num_parent,num_child);
}
cout<<tree.getHeight()<<endl;
return
0;
}
|
解法二:
#include <iostream>
#include <vector>
using
namespace
std;
int
main()
{
int
n,H = 1;
int
i = 0;
int
f,c, h;
vector<
int
> nodes(1000, 0);
//有效节点的高度
nodes[0] = 1;
// 题目说了至少有一个节点,高度只是是1
vector<
int
> childnum(1000, 0);
//记录节点的孩子数量
cin >> n;
while
(--n){
cin >> f >> c;
//父节点不存在 或者 父节点已有两个子节点 就跳过
if
(nodes[f]==0 || childnum[f] == 2)
continue
;
childnum[f] += 1;
h = nodes[f] + 1;
nodes[c] = h;
if
(h > H) H = h;
}
cout << H;
return
0;
}
|