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); };
- Time complexity: O(n)
- Space complexity: O(n)
Solved using bottom-up recursion.
Top comments (1)
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;
}
}
}