DEV Community

Masaki Fukunishi
Masaki Fukunishi

Posted on

LeetCode #104 Maximum Depth of Binary Tree with JavaScript

Solution to LeetCode's 104. Maximum Depth of Binary Tree with JavaScript.

Solution

/**
 * @param {TreeNode} root
 * @return {number}
 */
const maxDepth = (root) => {
  if (!root) return 0;
  const left = 1 + maxDepth(root.left);
  const right = 1 + maxDepth(root.right);
  return Math.max(left, right);
};
Enter fullscreen mode Exit fullscreen mode
  • Time complexity: O(n)
  • Space complexity: O(n)

Solved using bottom-up recursion.

Top comments (1)

Collapse
 
kompjuterbiblioteka profile image
Kompjuter biblioteka

ChatGPT answer is:

function maxDepth(node) {
if (node === null) {
return 0;
}
else {
var leftDepth = maxDepth(node.left);
var rightDepth = maxDepth(node.right);
if (leftDepth > rightDepth) {
return leftDepth + 1;
}
else {
return rightDepth + 1;
}
}
}