226. Invert Binary Tree ๐
Last updated
Was this helpful?
Last updated
Was this helpful?
Difficulty: Easy
- Tags: Binary Tree
, DFS
, BFS
, Recursion
Given the root of a binary tree, invert the tree (swap the left and right subtrees), and return its root.
๐น Example 1:
Input:
Output:
๐น Example 2:
Input:
Output:
๐น Example 3:
Input:
Output:
The number of nodes in the tree is in the range [0, 100]
.
-100 <= Node.val <= 100
.
To invert a binary tree:
Swap the left and right children of the current node.
Recursively apply the same operation for each child.
Base Case: If the current node is null
, return null
.
Swap the left and right children of the node.
Recursively call invertTree
for the left and right subtrees.
Return the root after performing all swaps.
O(n), where n
is the number of nodes in the tree. Each node is visited once.
O(h) for the recursive approach, where h
is the height of the tree (stack space for recursion).
O(n) for the iterative approach due to the queue.
How would you modify the solution for a n-ary tree?
Implement a solution to invert a binary tree in postorder traversal.