6 May 2024

Easy

226. Invert Binary Tree

Link: https://leetcode.com/problems/invert-binary-tree

Description: Given the root of a binary tree, invert the tree, and return its root.

Solution:

The idea is to invert the left and right subtrees of the current node recursively. Firstly we check if the root is null, in which case we return null. Then we swap the left and right children of the current node with help of a temporary variable. Finally, we recursively invert the left and right subtrees of the current node.

/**
 * 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 (root === null) {
    return null
  }

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

  invertTree(root.left)
  invertTree(root.right)

  return root
}