File tree Expand file tree Collapse file tree 1 file changed +21
-34
lines changed
src/main/java/com/fishercoder/solutions Expand file tree Collapse file tree 1 file changed +21
-34
lines changed Original file line number Diff line number Diff line change 2
2
3
3
import com .fishercoder .common .classes .TreeNode ;
4
4
5
- /**Given a binary tree, count the number of uni-value subtrees.
6
-
7
- A Uni-value subtree means all nodes of the subtree have the same value.
8
-
9
- For example:
10
- Given binary tree,
11
- 5
12
- / \
13
- 1 5
14
- / \ \
15
- 5 5 5
16
- return 4.
17
-
18
- */
<
10000
/td>19
5
public class _250 {
20
6
21
- public int countUnivalSubtrees (TreeNode root ) {
22
- int [] count = new int [1 ];
23
- helper (root , count );
24
- return count [0 ];
25
- }
26
-
27
- private boolean helper (TreeNode node , int [] count ) {
28
- if (node == null ) {
29
- return true ;
7
+ public static class Solution1 {
8
+ public int countUnivalSubtrees (TreeNode root ) {
9
+ int [] count = new int [1 ];
10
+ helper (root , count );
11
+ return count [0 ];
30
12
}
31
- boolean left = helper (node .left , count );
32
- boolean right = helper (node .right , count );
33
- if (left && right ) {
34
- if (node .left != null && node .val != node .left .val ) {
35
- return false ;
13
+
14
+ private boolean helper (TreeNode node , int [] count ) {
15
+ if (node == null ) {
16
+ return true ;
36
17
}
37
- if (node .right != null && node .val != node .right .val ) {
38
- return false ;
18
+ boolean left = helper (node .left , count );
19
+ boolean right = helper (node .right , count );
20
+ if (left && right ) {
21
+ if (node .left != null && node .val != node .left .val ) {
22
+ return false ;
23
+ }
24
+ if (node .right != null && node .val != node .right .val ) {
25
+ return false ;
26
+ }
27
+ count [0 ]++;
28
+ return true ;
39
29
}
40
- count [0 ]++;
41
- return true ;
30
+ return false ;
42
31
}
43
- return false ;
44
32
}
45
-
46
33
}
You can’t perform that action at this time.
0 commit comments