-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathUniVal.java
83 lines (71 loc) · 1.94 KB
/
UniVal.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
75
76
77
78
79
80
81
82
83
/*
Good morning! Here's your coding interview problem for today.
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
*/
class TreeNode{
int val;
TreeNode left,right;
TreeNode(int x){
val=x;
left=null;
right=null;
}
}
class Count{
int c=0;
}
class UniVal{
public static TreeNode root;
Count ct = new Count();
public int uniCount(TreeNode root)
{
uniCountHelper(root,ct);
return ct.c;
}
public boolean uniCountHelper(TreeNode root, Count count)
{
boolean left,right;
if(root==null) return true;
left = uniCountHelper(root.left,count);
right = uniCountHelper(root.right,count);
if(left!=true||right!=true)return false;
if(root.left!=null && root.val!=root.left.val)return false;
if(root.right!=null && root.val!=root.right.val)return false;
count.c++;
return true;
}
public boolean uniCountChecker(TreeNode root)
{
boolean left,right;
if(root==null) return true;
left = uniCountChecker(root.left);
right = uniCountChecker(root.right);
if(left!=true||right!=true)return false;
if(root.left!=null && root.val!=root.left.val)return false;
if(root.right!=null && root.val!=root.right.val)return false;
return true;
}
public static void main(String[] a)
{
UniVal tree = new UniVal();
tree.root = new TreeNode(1);
tree.root.left = new TreeNode(1);
tree.root.right = new TreeNode(1);
tree.root.left.left = new TreeNode(1);
tree.root.left.right = new TreeNode(1);
tree.root.right.left = new TreeNode(1);
tree.root.right.right = new TreeNode(1);
System.out.println(tree.uniCount(root));
System.out.println(tree.uniCountChecker(root));
}
}