
Problem
Solution
Submissions
Invert Binary Tree
Certification: Basic Level
Accuracy: 0%
Submissions: 0
Points: 5
Write a C program to invert a binary tree. To invert a binary tree, we need to swap the left and right children for each node in the tree. The inverted tree should be a mirror reflection of the original tree.
Example 1
- Input:
- Output:
- Explanation:
- Step 1: Swap the left and right children of the root node (4): 2 and 7 are swapped
- Step 2: Swap the left and right children of node 2: 1 and 3 are swapped
- Step 3: Swap the left and right children of node 7: 6 and 9 are swapped
- Step 4: The resulting tree is the mirror image of the original tree
Example 2
- Input:
- Output:
- Explanation:
- Step 1: Swap the left and right children of the root node (1): 2 and 3 are swapped
- Step 2: Node 2 has only one child (4), so after swapping, 4 becomes the left child
- Step 3: Node 3 has no children, so no further action is needed
- Step 4: The resulting tree is the mirror image of the original tree
Constraints
- The number of nodes in the tree is in the range [0, 100]
- -100 ≤ Node.val ≤ 100
- Time Complexity: O(n), where n is the number of nodes
- Space Complexity: O(h), where h is the height of the tree (due to recursion stack)
Editorial
My Submissions
All Solutions
Lang | Status | Date | Code |
---|---|---|---|
You do not have any submissions for this problem. |
User | Lang | Status | Date | Code |
---|---|---|---|---|
No submissions found. |
Solution Hints
- Use a recursive approach to traverse the tree
- For each node, swap its left and right children
- Recursively invert the left subtree and right subtree
- Handle leaf nodes and NULL pointers appropriately
- The base case is when the node is NULL
- The tree is built bottom-up as recursion unwinds