-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathProblem8.java
74 lines (58 loc) · 1.44 KB
/
Problem8.java
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
/***
* This problem was asked by Google.
*
* A unival tree (which stands for "universal value") is a tree where all nodes under it have the same value.
*
* Given the root to a binary tree, count the number of unival subtrees.
*
* For example, the following tree has 5 unival subtrees:
*
* 0
* / \
* 1 0
* / \
* 1 0
* / \
* 1 1
*
*/
public class Problem8 {
public static void main(String[] args) {
UNode root = new UNode(
0,
new UNode(1),
new UNode(0,
new UNode(1,
new UNode(1),
new UNode(1)
),
new UNode(0)
)
);
System.out.println(root.numOfUniValTree());
}
}
class UNode {
int value;
UNode left, right;
public UNode(int value) {
this(value, null, null);
}
public UNode (int value, UNode left, UNode right) {
this.value = value;
this.left = left;
this.right = right;
}
public int numOfUniValTree(){
if (left == null && right == null)
return 1;
int uniValTrees = 0;
if (left != null)
uniValTrees += left.numOfUniValTree();
if (right != null)
uniValTrees += right.numOfUniValTree();
if (left.value == right.value)
uniValTrees++;
return uniValTrees;
}
}