-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathP_250.java
More file actions
34 lines (29 loc) · 762 Bytes
/
Copy pathP_250.java
File metadata and controls
34 lines (29 loc) · 762 Bytes
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
package leetcode.medium;
import utils.DataStructures.TreeNode;
public class P_250 {
int count;
public int countUnivalSubtrees(TreeNode root) {
if (root == null) {
return 0;
}
dfs(root);
return count;
}
private boolean dfs(TreeNode node) {
if (node.left == null && node.right == null) {
count++;
return true;
}
boolean isUnival = true;
if (node.left != null) {
isUnival = dfs(node.left) && node.left.val == node.val;
}
if (node.right != null) {
isUnival &= dfs(node.right) && node.right.val == node.val;
}
if (isUnival) {
count++;
}
return isUnival;
}
}