Hi, I'm Rodo 👋

I'm a Software Engineer

Rodolfo Guluarte Hale

Hi, I'm Rodo 👋

I'm a Software Engineer

LeetCode: [226] Invert Binary Tree

1 minutes
February 11, 2023

Solution

For this problem we just solve the base problem for a tree with children, and then we use recursion to bubble up the changes.

/**
 * 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) return null

  const right = root.right
  const left = root.left

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

  
  return root
}