DevPath

← All problems

Maximum Depth of a Binary Tree

Easy trees · recursion

Description

Trees are given as a heap-style array (children of index i are 2i+1 and 2i+2, null means missing). Return the number of nodes on the longest root-to-leaf path.

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)
}

Create a free account to submit solutions, track progress and save problems.

Create account