814. Binary Tree Pruning

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
class Solution {
public TreeNode pruneTree(TreeNode root) {
if (root == null) {
return null;
}

root.left = pruneTree(root.left);
root.right = pruneTree(root.right);

if (root.val == 0 && root.left == null && root.right == null) {
// 仅值为 0 的叶子节点可消除
return null;
} else {
return root;
}
}
}

References

814. Binary Tree Pruning
剑指 Offer II 047. 二叉树剪枝