A records office stores its folders in a binary search tree: every folder holds a unique numeric ID, every folder in a subtree's left branch has a smaller ID than the folder above it, and every folder in the right branch has a larger ID. For a full audit, the office wants to walk every folder exactly once along a single straight corridor, from the smallest ID to the largest, with each folder leading directly to the next.
You are given the archive's current tree structure. Determine the order in which folders are visited when the tree is flattened into this single ascending corridor (equivalently: the archive's smallest-ID folder becomes the head of the corridor, the next folder in the corridor is the next-larger ID, and so on up to the largest folder).
The tree is given using the standard breadth-first (level-order) array notation for binary trees, where each node's two child slots are written immediately after all slots at the previous level (as in the familiar bracketed form [5,3,6,2,4,null,8]), and the literal token null marks a missing child. Trailing tokens for nodes that would only produce null null may be omitted from the end of the stream.
Line 1: a single integer T — the number of tokens.
Line 2: T space-separated tokens; each is either a folder ID (a non-negative integer) or the literal null. The first token is the root and is guaranteed not to be null.
A single line with every folder ID in the tree printed in strictly increasing order, space-separated.
Example 1
Input
13 5 3 6 2 4 null 8 null null null null null null
Expected
2 3 4 5 6 8
Explanation
The tree has root 5 with left child 3 and right child 6; 3 has children 2 and 4; 6 has a null left child and right child 8; nodes 2, 4, and 8 are leaves. Visiting the folders from smallest to largest ID gives 2, 3, 4, 5, 6, 8.
Example 2
Input
3 7 null null
Expected
7
Explanation
The archive holds a single folder with ID 7 and no children, so the corridor consists of just that one folder: 7.
Ready to solve this?
Sign in to open the editor, run your code against the sample tests, and submit against the full test suite.
Sign in to solve →