Overview
Given the root of a binary tree, return its maximum depth — the number of nodes along the longest path from the root node down to the farthest leaf node.
A tree with a single node has depth 1. An empty tree (null root) has depth 0.
Constraints
- The tree can have 0 to 10,000 nodes.
- Node values are integers (irrelevant to the solution).
- Return an integer representing the depth.
Examples
// Tree:
// 1
// / \
// 2 3
// /
// 4
maxDepth({ val: 1, left: { val: 2, left: { val: 4, left: null, right: null }, right: null }, right: { val: 3, left: null, right: null } });
// => 3// Single node
maxDepth({ val: 1, left: null, right: null });
// => 1
// Empty tree
maxDepth(null);
// => 0Solution
Reveal solution
function maxDepth(root) {
if (root === null) return 0;
return 1 + Math.max(maxDepth(root.left), maxDepth(root.right));
}Resources
binary-tree-max-depth.js
Binary Tree Maximum Depth
easycodingAlgorithmsTrees
Overview
Given the root of a binary tree, return its maximum depth — the number of nodes along the longest path from the root node down to the farthest leaf node.
A tree with a single node has depth 1. An empty tree (null root) has depth 0.
Constraints
- The tree can have 0 to 10,000 nodes.
- Node values are integers (irrelevant to the solution).
- Return an integer representing the depth.
Examples
// Tree:
// 1
// / \
// 2 3
// /
// 4
maxDepth({ val: 1, left: { val: 2, left: { val: 4, left: null, right: null }, right: null }, right: { val: 3, left: null, right: null } });
// => 3// Single node
maxDepth({ val: 1, left: null, right: null });
// => 1
// Empty tree
maxDepth(null);
// => 0Solution
Reveal solution
function maxDepth(root) {
if (root === null) return 0;
return 1 + Math.max(maxDepth(root.left), maxDepth(root.right));
}Resources
NameTopicDifficulty
103 of 103 problems