Invert Binary Tree
easyTrees+10 XPTime limit 2s
Mirror the tree: swap the left and right child of every node. Print the inverted tree.
Tree format. A binary tree is given on one line in level order (top to bottom, left to right), with null for a missing child — the same way most interview platforms show trees. Trailing nulls are left out, and an empty tree is the single word null. Example: 3 9 20 null null 15 7 is
3
/ \
9 20
/ \
15 7
Input: one tree.
Output: the inverted tree in the same level-order format.
Constraints: 0 ≤ nodes ≤ 10⁴. The tree has at most 10⁴ nodes and its height is at most 500, so recursion is safe in every language.
Think about it: swap the children of the root, then invert both subtrees — recursion or a queue both work. You also need to print a tree in level order: BFS, printing null for missing children, then drop the trailing nulls.
Sample input 1
4 2 7 1 3 6 9
Sample output 1
4 7 2 9 6 3 1
Sample input 2
2 1 3
Sample output 2
2 3 1
📖 Stuck? Learn the pattern
Read input from standard input and print the answer to standard output. Your code runs in a secure sandbox against the samples (Run) and hidden tests (Submit).