#K43692. Prune Tree: Removing All-Zero Subtrees
Prune Tree: Removing All-Zero Subtrees
Prune Tree: Removing All-Zero Subtrees
You are given a binary tree where each node has a value of either 0 or 1. Your task is to prune the tree by removing any subtree that consists entirely of nodes with the value 0. The pruning is performed recursively: after pruning the left and right subtrees, if a node’s value is 0 and both of its subtrees are pruned (i.e. they are null), then that node itself should also be pruned (removed).
The binary tree is provided as a serialized, comma-separated list of node values in level-order format, with null
indicating missing nodes. After pruning, output the resulting tree in the same format. Note that trailing null
values should be omitted for a compact representation.
inputFormat
The input is a single line containing a comma-separated list of node values representing the binary tree in level-order. Use null
to indicate empty (missing) nodes.
For example: 1,0,1,0,0
outputFormat
Output the pruned binary tree as a comma-separated list of node values in level-order. Do not include trailing null
tokens.
For example: 1,null,1
1,0,1,0,0
1,null,1