FastPrepPrune All-Zero Binary Tree Subtrees

Prune All-Zero Binary Tree Subtrees

Amazon logoAmazon● MediumFULLTIMEONSITE INTERVIEW
Learn

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) → TreeNode

Examples

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 0 through 500 nodes.
  • -10^6 <= node.val <= 10^6.

More Amazon problems

See Amazon hiring insights
public TreeNode pruneZeroSubtrees(TreeNode root) {
    // Write your code here
}
root[1,0,3,0,null,0,4]
expected[1,null,3,null,4]
Checking account…