Invert Binary Tree
Explore how to invert a binary tree by swapping each node's left and right subtrees recursively. Understand the process of creating a mirror image of a tree and gain practical experience solving this fundamental tree transformation problem.
We'll cover the following...
Statement
Given the root node of a binary tree, transform the tree by swapping each node’s left and right subtrees, thus creating a mirror image of the original tree. Return the root of the transformed tree.
Constraints:
- Number of nodes in the tree
-
Node.value
Examples
Understand the problem
Let’s take a moment to make sure you’ve correctly understood the problem. The quiz below helps you check if you’re solving the correct problem:
Invert Binary Tree
What is the correct mirrored tree for the given tree?
5
/ \
6 7
/ \
8 9
5
/ \
6 7
/ \
8 9
5
/ \
7 6
/ \
9 8
5
/ \
6 7
/ \
9 8
5
/ \
7 6
/ \
9 8
Figure it out!
We have a game for you to play. Rearrange the logical building blocks to develop a clearer understanding of how to solve this problem.
Try it yourself
Implement your solution in main.java in the following coding playground.
// Definiton of a binary tree node class// class TreeNode<T> {// T data;// TreeNode<T> left;// TreeNode<T> right;// TreeNode(T data) {// this.data = data;// this.left = null;// this.right = null;// }// }import java.util.*;import ds_v1.BinaryTree.TreeNode;public class Solution{public static TreeNode<Integer> invertTree(TreeNode<Integer> root){// Replace this placeholder return statement with your codereturn root;}}