Invert Binary Tree
Given the root of a binary tree, flip the whole tree into its mirror image and return the new root. "Inverting" means that at every single node, its left and right children trade places.
Input Format
Implement invertBinaryTree(root). Inputs below show JavaScript function arguments; there is no stdin parsing.
Trees use level-order arrays with null for missing children. The editor passes nodes with val, left, and right properties; [] becomes null.
Output Format
Return the result described in the statement.
Returned trees are displayed as level-order arrays, trimming trailing nulls.
Sample Input and Output
Example 1 ยท Run Sample
Input
root = [4,2,7,1,3,6,9] Output
[4,7,2,9,6,3,1] Example 2
Input
root = [2,1,3] Output
[2,3,1] Example 3
Input
root = [] Output
[] Constraints
- 0 <= number of nodes <= 100
- -100 <= Node.val <= 100
Test Cases (3)
Case 1
Args: [[4,2,7,1,3,6,9]]
Expected: [4,7,2,9,6,3,1]
Case 2
Args: [[2,1,3]]
Expected: [2,3,1]
Case 3
Args: [[]]
Expected: []
Topics
Approach: Recursive DFS
For each node, swap its left and right children, then recursively invert both subtrees. Base case: null node returns null.
function invertBinaryTree(root) {
if (!root) return null;
[root.left, root.right] = [root.right, root.left];
invertBinaryTree(root.left);
invertBinaryTree(root.right);
return root;
}Time Complexity: O(n)
Space Complexity: O(h) where h is tree height
Saved in this browser only. Private to you.