Invert Binary Tree LeetCode

Given the root of a Binary Tree, invert the tree, and return its root.

 Example 1:

Input: root = [4,2,7,1,3,6,9]
Output: [4,7,2,9,6,3,1]

Example 2:

Input: root = [2,1,3]
Output: [2,3,1]

Example 3:

Input: root = []
Output: []

 NOTE:

  • The number of nodes in the tree is in the range [0, 100].
  • -100 <= Node.val <= 100
Trivia:
This problem was inspired by this original tweet by Max Howell:
Google: 90% of our engineers use the software you wrote (Homebrew), but you can’t invert a binary tree on a whiteboard so fuck off.
This problem is popular in LeetCode, StackOverFlow and several other forums - Ref 1 A collection of hundreds of interview questions and solutions are available in our blog at Interview Question Solutions

Solution:
/**
*
* Invert a binary tree.
4
/ \
2 7
/ \ / \
1 3 6 9
to
4
/ \
7 2
/ \ / \
9 6 3 1
*
*
* Solution:
* The basic idea here is to switch the right and left child of a node. This process should recursively applied
* to all the nodes which have the child nodes.
*
*
* @author rbaral
*/
public class InvertBinaryTree {
TreeNode root = null;
public InvertBinaryTree(){
}
public TreeNode invertTree(TreeNode node){
if(node==null){
return node;
}else{
TreeNode n = node.left;
node.left = node.right;
node.right = n;
invertTree(node.left);
invertTree(node.right);
}
return node;
}
public static void main(String args[]){
InvertBinaryTree inv = new InvertBinaryTree();
//lets create a binary tree
TreeNode btree = new TreeNode(4);
TreeNode lvl1_left = new TreeNode(2);
TreeNode lvl1_right = new TreeNode(7);
btree.left = lvl1_left;
btree.right = lvl1_right;
TreeNode lvl2_left_l = new TreeNode(1);
TreeNode lvl2_left_r = new TreeNode(3);
lvl1_left.left = lvl2_left_l;
lvl1_left.right = lvl2_left_r;
TreeNode lvl2_right_l = new TreeNode(6);
TreeNode lvl2_right_r = new TreeNode(9);
lvl1_right.left = lvl2_right_l;
lvl1_right.right = lvl2_right_r;
btree.printInOrderTree();
TreeNode invTree = inv.invertTree(btree);
invTree.printInOrderTree();
}
}

No comments:

Post a Comment