Prune All-Zero Binary Tree Subtrees
Problem statement
Remove every binary-tree subtree whose node values are all 0. Return the root of the remaining tree. A nonzero value anywhere in a subtree prevents that subtree from being removed.
For this exercise, assume signed integer values: a zero sum caused by positive and negative cancellation does not make a subtree all-zero. An empty tree remains empty, and an all-zero tree disappears. The required solution takes O(n) time.
Function
pruneZeroSubtrees(root: TreeNode) → TreeNodeExamples
Example 1
root = [1,0,3,0,null,0,4]return = [1,null,3,null,4]Removing matching leaves can expose another removable matching leaf.
Example 2
root = [0,0,0]return = []The entire tree disappears when every node is removable.
Example 3
root = []return = []An empty tree remains empty.
Constraints
- For this exercise, assume a finite acyclic binary tree containing
0through500nodes. -10^6 <= node.val <= 10^6.