forked from jj20/Codility-2
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathTreeHeight
51 lines (44 loc) · 2.14 KB
/
TreeHeight
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
Task description
In this problem we consider binary trees, represented by pointer data-structures. A pointer is called a binary tree if:
it is an empty pointer (it is then called an empty tree); or
it points to a structure (called a node) that contains a value and two pointers that are binary trees (called the left subtree and the right subtree).
A figure below shows a tree consisting of six nodes.
A path in a binary tree is a sequence of nodes one can traverse by following the pointers. More formally, a path is a sequence of nodes P[0], P[1], ..., P[K], such that node P[L] contains a pointer pointing to P[L + 1], for 0 ≤ L < K. K is called the length of such a path.
The height of a binary tree is defined as the length of the longest possible path in the tree. In particular, a tree consisting only of just one node has height 0 and the height of an empty tree is undefined.
For example, consider the following tree:
Subtrees of nodes D, E and F are empty trees. Sequence A, B, E is a path of length 2. Sequence C, F is a path of length 1. Sequence E, B, D is not a valid path. The height of this tree is 2.
Assume that the following declarations are given:
class Tree {
public int x;
public Tree l;
public Tree r;
}
Write a function:
class Solution { public int solution(Tree T); }
that, given a non-empty binary tree T consisting of N nodes, returns its height.
For example, given tree T shown in the example above, the function should return 2.
Assume that:
N is an integer within the range [1..1,000].
Complexity:
expected worst-case time complexity is O(N);
expected worst-case space complexity is O(N).
Solution:
// you can also use imports, for example:
// import java.math.*;
class Solution {
public int solution(Tree T){
return solution(T, T);
}
public int solution(Tree T, Tree root) {
// write your code in Java SE 7
if(T==null)
return 0;
int lheight=0, rheight=0;
lheight=solution(T.l, root);
rheight=solution(T.r, root);
if(T==root)
return Math.max(lheight,rheight);
else
return Math.max(lheight+1,rheight+1);
}
}