-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathBinaryTreePruner.java
45 lines (38 loc) · 1011 Bytes
/
BinaryTreePruner.java
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
package org.sean.tree;
/***
* 814. Binary Tree Pruning
*/
public class BinaryTreePruner {
private boolean bePrunable(TreeNode node) {
if(node != null) {
boolean leftPrunable = true;
boolean rightPrunable = true;
if(node.left != null) {
leftPrunable = bePrunable(node.left);
}
if(node.right != null) {
rightPrunable = bePrunable(node.right);
}
if(leftPrunable) {
node.left = null;
}
if(rightPrunable) {
node.right = null;
}
if(node.val == 0) {
if(leftPrunable && rightPrunable)
return true;
}
return false;
}
return true;
}
public TreeNode pruneTree(TreeNode root) {
if(root != null) {
if(bePrunable(root)) {
root = null;
}
}
return root;
}
}