7 May 2024

Easy

104. Maximum Depth of Binary Tree

Link: https://leetcode.com/problems/maximum-depth-of-binary-tree

Description: Given the root of a binary tree, return its maximum depth.

Solution:

The idea is to recursively calculate the maximum depth of the left and right subtrees of the current node. The maximum depth of the current node is the maximum of the maximum depth of the left and right subtrees plus one. If the root is null, we return null. Otherwise, we recursively calculate the maximum depth of 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 0
  }

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

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

  return root
}