Perform a preorder traversal of the binary tree: visit the current node first, then its left subtree, then its right subtree. Output the visited values in that order.
One line: the binary tree as a level-order array.
The tree is encoded on ONE line as a space-separated level-order (breadth-first) array. The token null marks a missing child; the children of a null are omitted from the array. An empty tree is written as the single token null.
One line: the node values in preorder, separated by single spaces. If the tree is empty, print an empty line.
Example 1
Input
1 2 3 4 5 null 6
Expected
1 2 4 5 3 6
Explanation
Visiting node then left then right gives 1, then the left subtree 2 4 5, then the right subtree 3 6: `1 2 4 5 3 6`.
Example 2
Input
1 2 3
Expected
1 2 3
Explanation
Root 1, then left child 2, then right child 3: `1 2 3`.
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 →