Binary Tree Pruning

Given the `root` of a binary tree whose node values are all `0` or `1`, return the same tree where every subtree not containing a `1` has been removed. A subtree of a node is the node itself plus all of its descendants.

30:00

Binary Tree Pruning
medium
Free written solution
Topics
Companies

Given the root of a binary tree whose node values are all 0 or 1, return the same tree where every subtree not containing a 1 has been removed.

A subtree of a node is the node itself plus all of its descendants.

Example 1:
Input: {"root":[1,null,0,0,1]}
Output: [1,null,0,null,1]
Constraints:
  • The number of nodes in the tree is in the range [1,200][1, 200].

  • Node.val is either 0 or 1.

Test Cases
Input (Stdin)
Expected Output (Stdout)
Execution Result

Run code to see results.

Input
arr ={"root":[1,null,0,0,1]}

Prune bottom-up: a node can only be judged after its children have been pruned. The tree has 4 nodes, 2 of them are 1.

kept 0
removed 0
stack: (empty)
1001
value 1
recursion stack
kept (subtree has a 1)
returned null (cut)
Variables
VariableValue
nodes4
ones2
DepthFunction Call
Stack empty
0/9