Tutorialspoint
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:

    Invert Binary Tree with Input of Root Node 4
  • Output:

     Invert Binary Tree with Output of Root Node 4
  • 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:

     Invert Binary Tree with Input of Root Node 1
  • Output:

    Invert Binary Tree with Output of Root Node 1


  • 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)
Binary TreeTech MahindraAdobe
Editorial

Login to view the detailed solution and explanation for this problem.

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.

Please Login to continue
Solve Problems

 
 
 
Output Window

Don't have an account? Register

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

Steps to solve by this approach:

 Step 1: Check if the root is NULL - if so, return NULL (base case)
 Step 2: Store the left child in a temporary variable
 Step 3: Assign the right child to be the new left child
 Step 4: Assign the temporary variable (original left child) to be the new right child
 Step 5: Recursively invert the left subtree
 Step 6: Recursively invert the right subtree
 Step 7: Return the root node with its subtrees inverted

Submitted Code :