📘
Invert Binary Tree
Given the root of a binary tree (as a level-order array), invert it (mirror/flip left and right children recursively).
Output the level-order traversal of the inverted tree as space-separated values.
Example:
Input:
4,2,7,1,3,6,9
Output:
4 7 2 9 6 3 1
Reasoning:
- The given binary tree has a root node with value 4, and its left and right children are 2 and 7, respectively.
- To invert the tree, we swap the left and right children of each node recursively: the left child of the root becomes 7 (with children 6 and 9), and the right child becomes 2 (with children 3 and 1).
- We then perform a level-order traversal of the inverted tree, visiting nodes in the order: root (4), children (7, 2), grandchildren (9, 6, 3, 1).
- The final output is the level-order traversal of the inverted tree as space-separated values: 4 7 2 9 6 3 1
Constraints:
- 0 <= number of nodes <= 100
- -100 <= Node.val <= 100
Editor
Python 3.13.1
Test Results
0/0Run code to see test results.