Invert Binary Tree
TreeDFSRecursion
Problem Statement
Given the root
of a binary tree, invert the tree, and return its root.
Example
Example 1:
Input:
Output:
Constraints
- The number of nodes in the tree is in the range [0, 100].
- -100 ≤ Node.val ≤ 100
Recursive Solution (DFS)
The recursive approach uses a Depth-First Search (DFS) strategy to traverse the tree and swap the left and right children of each node.
Algorithm Steps
- The base case for the recursion is when a node is
null
, in which case we returnnull
. - Recursively call the function on the left and right children.
- Swap the left and right children of the current node.
- Return the current node.
Start: Call invertTree on root (4).
Invert Binary Tree Solution
Iterative Solution (BFS with Queue)
The iterative solution uses a queue to perform a Breadth-First Search (BFS). We traverse the tree level by level and swap the children of each node.
Algorithm Steps
- If the root is
null
, returnnull
. - Create a queue and add the root node.
- While the queue is not empty, dequeue a node.
- Swap the left and right children of the dequeued node.
- If the left child is not
null
, add it to the queue. - If the right child is not
null
, add it to the queue. - After the loop, return the root.
Invert Binary Tree Solution