EasyPythonJavaScriptTypeScript
Binary Tree — Invert a Tree
Data StructuresTreesRecursionDFS
Mirror a binary tree: at every node, swap the left and right children.solve(levelOrder) builds the tree from a level-order array, inverts it and
returns it serialized again with the provided toLevelOrder helper.
Examples
solve([4, 2, 7, 1, 3, 6, 9]) → [4, 7, 2, 9, 6, 3, 1]
solve([2, 1, 3]) → [2, 3, 1]
solve([1, 2]) → [1, null, 2]
solve([]) → []Swapping only the root's children is the classic mistake — the swap has to
happen all the way down.
Sample tests
Test #1Perfect tree
Input: [[4,2,7,1,3,6,9]]
Output: [4,7,2,9,6,3,1]
Test #2Three nodes
Input: [[2,1,3]]
Output: [2,3,1]
Test #3Empty tree
Input: [[]]
Output: []