Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
Skip to content

Commit e356669

Browse files
count univalue subtrees
1 parent 0ff1c87 commit e356669

File tree

2 files changed

+33
-0
lines changed

2 files changed

+33
-0
lines changed
Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
package medium;
2+
3+
import classes.TreeNode;
4+
5+
public class CountUnivalueSubtrees {
6+
7+
public int countUnivalSubtrees(TreeNode root) {
8+
int[] count = new int[1];
9+
helper(root, count);
10+
return count[0];
11+
}
12+
13+
private boolean helper(TreeNode node, int[] count) {
14+
if (node == null) {
15+
return true;
16+
}
17+
boolean left = helper(node.left, count);
18+
boolean right = helper(node.right, count);
19+
if (left && right) {
20+
if (node.left != null && node.val != node.left.val) {
21+
return false;
22+
}
23+
if (node.right != null && node.val != node.right.val) {
24+
return false;
25+
}
26+
count[0]++;
27+
return true;
28+
}
29+
return false;
30+
}
31+
32+
}

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -63,6 +63,7 @@
6363
|259|[3Sum Smaller](https://leetcode.com/problems/3sum-smaller/)|[Solution](../../blob/master/MEDIUM/src/medium/_3Sum_Smaller.java)| O(n^2)|O(1) | Medium|
6464
|257|[Binary Tree Paths](https://leetcode.com/problems/binary-tree-paths/)|[Solution](../../blob/master/EASY/src/easy/BinaryTreePaths.java) | O(n*h) | O(h) | DFS/Recursion
6565
|252|[Meeting Rooms](https://leetcode.com/problems/meeting-rooms/)|[Solution](../../blob/master/EASY/src/easy/MeetingRooms.java) | O(nlogn) | O(1) |
66+
|250|[Count Univalue Subtrees](https://leetcode.com/problems/count-univalue-subtrees/)|[Solution](../../blob/master/MEDIUM/src/medium/CountUnivalueSubtrees.java)| O(n)|O(h) | Medium| DFS
6667
|249|[Group Shifted Strings](https://leetcode.com/problems/group-shifted-strings/)|[Solution](../../blob/master/EASY/src/easy/GroupShiftedStrings.java) | O(nlogn) | O(n) |
6768
|246|[Strobogrammatic Number](https://leetcode.com/problems/strobogrammatic-number/)|[Solution](../../blob/master/EASY/src/easy/StrobogrammaticNumber.java) | O(n) | O(1) |
6869
|243|[Shortest Word Distance](https://leetcode.com/problems/shortest-word-distance/)|[Solution](../../blob/master/EASY/src/easy/ShortestWordDistance.java) | O(n) | O(1) |

0 commit comments

Comments
 (0)