All problems

Problem 916

Binary Tree Pruning

Medium · 20 pts · Tree, Depth-First Search

Problem

Every node of the binary tree holds 0 or 1. Remove every subtree that does not contain a 1, and print the resulting tree, or EMPTY if no 1 exists at all. A post-order traversal does it in one pass: prune both children first, and then remove the current node if its value is 0 and it has no children left.

Input

The first line contains N, the number of tokens. The second line contains N tokens describing the tree in level order (breadth-first, left to right), where 'null' marks a missing child, as on LeetCode. Every value is 0 or 1.

Output

Print the tree as level-order tokens separated by spaces, using null for missing children and without trailing nulls, or EMPTY if nothing remains.

Constraints

1 <= number of nodes <= 200

Example input

5
1 null 0 0 1

Example output

1 null 0 null 1

Explanation

In 1 null 0 0 1, the left child 0 of the node 0 has no 1 below it, so it is removed. The result is 1 null 0 null 1.

Every problem here can be used in a RelayTrixCode team match. Create a room.

Previous: Insufficient Nodes in Root to Leaf Paths Next: Find Duplicate Subtrees