-
Notifications
You must be signed in to change notification settings - Fork 9
Expand file tree
/
Copy pathCountUnivalueSubtrees.java
More file actions
50 lines (47 loc) · 1.58 KB
/
CountUnivalueSubtrees.java
File metadata and controls
50 lines (47 loc) · 1.58 KB
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
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public int countUnivalSubtrees(TreeNode root) {
int[] count = {0};
isUnivalue(root, count);
return count[0];
}
public boolean isUnivalue(TreeNode root, int[] count) {
if (root == null) return true;
boolean leftIs = isUnivalue(root.left, count);
boolean rightIs = isUnivalue(root.right, count);
boolean is = false;
if (leftIs && rightIs) {
if ((root.left != null && root.right != null && root.left.val == root.val && root.right.val == root.val)
|| (root.left != null && root.right == null && root.left.val == root.val)
|| (root.left == null && root.right != null && root.right.val == root.val)
|| (root.left == null && root.right == null)) {
count[0]++;
is = true;
}
}
return is;
}
}
public class Solution {
public int countUnivalSubtrees(TreeNode root) {
int[] count = {0};
isUnivalue(root, 0, count);
return count[0];
}
public boolean isUnivalue(TreeNode root, int value, int[] count) {
if (root == null) return true;
boolean leftIs = isUnivalue(root.left, root.val, count);
boolean rightIs = isUnivalue(root.right, root.val, count);
if (!leftIs || !rightIs) return false;
count[0]++;
return root.val == value;
}
}