-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathcount-univalue-subtrees.java
50 lines (48 loc) · 1.39 KB
/
count-univalue-subtrees.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
/* package whatever; // don't place package name! */
import java.util.*;
import java.lang.*;
import java.io.*;
/* Name of the class has to be "Main" only if the class is public. */
class Ideone
{
static class TreeNode {
int val;
TreeNode left, right;
public TreeNode(int value) {this.val = value;}
}
public static void main (String[] args) throws java.lang.Exception
{
TreeNode root = new TreeNode(5);
root.left = new TreeNode(1);
root.right = new TreeNode(5);
root.left.left = new TreeNode(5);
root.left.right = new TreeNode(5);
root.right.right = new TreeNode(5);
System.out.println(countUnivalSubtrees(root));
}
public static int countUnivalSubtrees(TreeNode root) {
if (root == null) return 0;
return countUnivals(root);
}
public static int countUnivals(TreeNode root) {
if (root.left == null && root.right == null) {
return 1;
} else if (root.left != null && root.right != null) {
int left = countUnivals(root.left);
int right = countUnivals(root.right);
if (root.left.val == root.val && root.right.val == root.val)
return 1 + right + left;
else return left + right;
} else if (root.left != null) {
int left = countUnivals(root.left);
if (root.left.val == root.val)
return left + 1;
else return left;
} else {
int right = countUnivals(root.right);
if (root.right.val == root.val)
return right + 1;
else return right;
}
}
}