Maximum Depth of a Binary Tree
Easy trees · recursion
Description
Constraints
0 <= n <= 100000
Examples
Input: tree = [3,9,20,null,null,15,7]
Output: 3
Hints (1)
- Depth is 1 plus the deeper of the two children.
Solutions
Recursive depth. · Time O(n) · Space O(h)
func treeMaxDepth(tree []interface{}) int {
var h func(int) int
h = func(i int) int {
if i >= len(tree) || tree[i] == nil {
return 0
}
l, r := h(2*i+1), h(2*i+2)
if l > r {
return 1 + l
}
return 1 + r
}
return h(0)
}
Recursive depth. · Time O(n) · Space O(h)
function treeMaxDepth(tree) {
const h = (i) => (i >= tree.length || tree[i] === null) ? 0 : 1 + Math.max(h(2 * i + 1), h(2 * i + 2));
return h(0);
}
Recursive depth. · Time O(n) · Space O(h)
function treeMaxDepth($tree) {
$h = function ($i) use (&$tree, &$h) {
if ($i >= count($tree) || $tree[$i] === null) return 0;
return 1 + max($h(2 * $i + 1), $h(2 * $i + 2));
};
return $h(0);
}
Recursive depth. · Time O(n) · Space O(h)
def treeMaxDepth(tree):
def h(i):
if i >= len(tree) or tree[i] is None:
return 0
return 1 + max(h(2 * i + 1), h(2 * i + 2))
return h(0)
Recursive depth. · Time O(n) · Space O(h)
function treeMaxDepth(tree: (number | null)[]): number {
const h = (i: number): number => (i >= tree.length || tree[i] === null) ? 0 : 1 + Math.max(h(2 * i + 1), h(2 * i + 2));
return h(0);
}
Create a free account to submit solutions, track progress and save problems.
Create account