Skip to content

Commit 49c9146

Browse files
Create count-univalue-subtrees.java
1 parent c88bb70 commit 49c9146

File tree

1 file changed

+50
-0
lines changed

1 file changed

+50
-0
lines changed

count-univalue-subtrees.java

Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
1+
/* package whatever; // don't place package name! */
2+
3+
import java.util.*;
4+
import java.lang.*;
5+
import java.io.*;
6+
7+
/* Name of the class has to be "Main" only if the class is public. */
8+
class Ideone
9+
{
10+
static class TreeNode {
11+
int val;
12+
TreeNode left, right;
13+
public TreeNode(int value) {this.val = value;}
14+
}
15+
public static void main (String[] args) throws java.lang.Exception
16+
{
17+
TreeNode root = new TreeNode(5);
18+
root.left = new TreeNode(1);
19+
root.right = new TreeNode(5);
20+
root.left.left = new TreeNode(5);
21+
root.left.right = new TreeNode(5);
22+
root.right.right = new TreeNode(5);
23+
System.out.println(countUnivalSubtrees(root));
24+
}
25+
public static int countUnivalSubtrees(TreeNode root) {
26+
if (root == null) return 0;
27+
return countUnivals(root);
28+
}
29+
public static int countUnivals(TreeNode root) {
30+
if (root.left == null && root.right == null) {
31+
return 1;
32+
} else if (root.left != null && root.right != null) {
33+
int left = countUnivals(root.left);
34+
int right = countUnivals(root.right);
35+
if (root.left.val == root.val && root.right.val == root.val)
36+
return 1 + right + left;
37+
else return left + right;
38+
} else if (root.left != null) {
39+
int left = countUnivals(root.left);
40+
if (root.left.val == root.val)
41+
return left + 1;
42+
else return left;
43+
} else {
44+
int right = countUnivals(root.right);
45+
if (root.right.val == root.val)
46+
return right + 1;
47+
else return right;
48+
}
49+
}
50+
}

0 commit comments

Comments
 (0)