Invert A Binary Tree:
Given the root
of a binary tree, invert the tree, and return its root.
Input: root = [4,2,7,1,3,6,9]
Output: [4,7,2,9,6,3,1]
Input: root = [2,1,3]
Output: [2,3,1]
Input: root = []
Output: []
[0, 100]
.-100 <= Node.val <= 100
Try this Problem on your own or check similar problems:
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
public TreeNode invertTree(TreeNode root) {
if(root == null) return null;
TreeNode temp = root.left;
root.left = invertTree(root.right);
root.right = invertTree(temp);
return root;
}
}
We use DFS (Depth First Search) approach, to traverse and invert tree, the only trap here is to consider destructive action on left subtree. We use temp
value to invert left subtree and assign it as right subtree (same as swapping two int values using a temp helper variable). Since we’re traversing the whole binary tree we will have linear time complexity proportional to the number of nodes in binary tree O(n)
, while for the space complexity if we have left or right skewed tree (every node is left child of its parent, and only node in its level or right child for right skewed tree) we would have a recursion stack of depth n
(number of nodes in binary tree) leading to linear space complexity O(n)
. Famous tweet
https://twitter.com/mxcl/status/608682016205344768
.
Don’t settle for anything less than the crown. Join our newsletter and become the King of Interviews! Click here to join now and get the latest updates.