Skip to content

Commit 560256d

Browse files
authored
Update Binary Tree Pruning.java
1 parent 295a892 commit 560256d

File tree

1 file changed

+7
-9
lines changed

1 file changed

+7
-9
lines changed

Medium/Binary Tree Pruning.java

+7-9
Original file line numberDiff line numberDiff line change
@@ -15,23 +15,21 @@
1515
*/
1616
class Solution {
1717
public TreeNode pruneTree(TreeNode root) {
18-
boolean isRootOne = helper(root);
19-
return isRootOne ? root : null;
18+
return subtreeContainsOne(root) ? root : null;
2019
}
2120

22-
private boolean helper(TreeNode root) {
21+
private boolean subtreeContainsOne(TreeNode root) {
2322
if (root == null) {
2423
return false;
2524
}
26-
boolean selfOne = root.val == 1;
27-
boolean leftContainsOne = helper(root.left);
28-
boolean rightContainsOne = helper(root.right);
29-
if (!leftContainsOne) {
25+
boolean leftContains = subtreeContainsOne(root.left);
26+
boolean rightContains = subtreeContainsOne(root.right);
27+
if (!leftContains) {
3028
root.left = null;
3129
}
32-
if (!rightContainsOne) {
30+
if (!rightContains) {
3331
root.right = null;
3432
}
35-
return selfOne || leftContainsOne || rightContainsOne;
33+
return leftContains || rightContains || root.val == 1;
3634
}
3735
}

0 commit comments

Comments
 (0)