#C14240. Pruning a Binary Tree
Pruning a Binary Tree
Pruning a Binary Tree
You are given a binary tree represented in level-order as a comma-separated string of values. Each value is either an integer or the keyword null
, which indicates the absence of a node. Your task is to prune the tree by removing all subtrees consisting solely of nodes with the value 0.
Formally, for every node in the tree, recursively remove its left and right subtrees if they contain no node with a nonzero value. In other words, if a node's value is 0 and both of its (pruned) children are null
, then that node should also be pruned (removed). If the entire tree is pruned away, output null
.
The input and output use level-order traversal format. See the examples for clarity.
Note: Any mathematical formulas, if needed, should be written in \( \LaTeX \) format. In this problem no such formulas are necessary.
inputFormat
The input consists of a single line containing a comma-separated list of values that represent the binary tree in level-order. Each value is either an integer or the string null
(without quotes) to denote a missing node.
For example: 1,null,0,0,1
outputFormat
Output the pruned binary tree in the same comma-separated level-order format. If the pruned tree is empty, output null
.
1,null,0,0,1
1,null,0,null,1