DEV Community

Subramanya Chakravarthy
Subramanya Chakravarthy

Posted on

Invert Binary Tree - LeetCode

Given a binary tree, you have to invert left and right nodes of it

Example:

Input

 4

/ \
2 7
/ \ / \
1 3 6 9

Output

 4

/ \
7 2
/ \ / \
9 6 3 1

Algorithm:

The intuition here is for each root node you visit swap left and right

The code would be something like

temp = root.left
root.left = root.right
root.right = temp

And we have to do this recursively for all the nodes

Code

/**
 * Definition for a binary tree node.
 * function TreeNode(val, left, right) {
 *     this.val = (val===undefined ? 0 : val)
 *     this.left = (left===undefined ? null : left)
 *     this.right = (right===undefined ? null : right)
 * }
 */
/**
 * @param {TreeNode} root
 * @return {TreeNode}
 */
var invertTree = function(root) {
  // If there is a root we swap it and if there is no root just return the value
  if(root) {
    let temp = root.left
    root.left = root.right
    root.right = temp  
    invertTree(root.left)
    invertTree(root.right)
  }
  return root
};

Top comments (0)