FastPrepPrune Subtrees That Hold Only Zeros

Prune Subtrees That Hold Only Zeros

Capital One logoCapital One● MediumINTERNNEW GRADONSITE INTERVIEW

Updated

Problem statement

Every node of the binary tree at root holds a non-negative whole number. Cut away each part of the tree that contains nothing but zeros, and return the root of what is left.

A node is kept exactly when it, or some node below it, holds a non-zero value. A zero node with a non-zero value somewhere beneath it therefore stays. If nothing is kept, return an empty tree.

Function

pruneTree(root: TreeNode) → TreeNode

Examples

Example 1

root = [5,0,0,0,7,0]return = [5,0,null,null,7]
root
500700
Removed
return
507

The left 0 under the root has a 7 below it, so it stays, but its own left child, a lone 0, goes. The right 0 under the root has only another 0 beneath it, so that whole branch goes.

Example 2

root = [0,null,0,0]return = []
root
000
return
empty

Every node is 0, so the whole tree is removed and the answer is empty.

Example 3

root = [0,0,2]return = [0,null,2]
root
002
Removed
return
02

The root is 0 but it stays, because 2 sits below it. Only the left 0, which has nothing below it, is removed.

Constraints

  • The number of nodes in the tree is between 0 and 1000.
  • 0 <= Node.val <= 10^4

More Capital One Onsite Interview questions

Similar questions at other companies

Capital One interview experiences

All Capital One interview questionsSee Capital One hiring insights
Saved
/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode() {}
 *     TreeNode(int val) { this.val = val; }
 *     TreeNode(int val, TreeNode left, TreeNode right) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */
class Solution {
    public TreeNode pruneTree(TreeNode root) {
        // Write your code here.
    }
}
Checking account…