Menu
CoddyTech

Maximum Depth of Binary Tree

You get a binary tree stored in the array tree in level order. The root sits at index 0, the children of the node at index i sit at 2*i+1 (left) and 2*i+2 (right), -1 marks an empty spot, and the array may end with extra -1 entries. Return the maximum depth of the tree: the number of nodes on the longest path from the root down to a leaf.

Function

maxDepth(tree: integer-array) → integer
treeinteger-array
the binary tree in level order, with -1 for an empty spot
Returnsinteger
the number of nodes on the longest root-to-leaf path

Constraints

  • 1 ≤ tree.length ≤ 32767
  • Each tree[i] is -1 or a value with 0 ≤ tree[i] ≤ 1000.
  • tree[0] is never -1, so the tree has at least one node.
  • The array may end with extra -1 entries past the last node.
  • Both children of an empty spot are empty too, and the depth is at most 14.

Examples

Input
tree = [5, 8, 1, -1, 3, -1, -1, -1, -1, 6]
Output
4
Explanation
The longest path is 5, 8, 3, 6 (indexes 0, 1, 4, 9), which holds 4 nodes. The path through 1 stops after 2 nodes.

lock icon+13 hidden tests on Submit

challenge icon

Follow-up

How would you return the values on a longest root-to-leaf path, not only its length? If several paths tie, which one would you return, and how would you say so in the contract?

Reset code
def maxDepth(tree):
    # Write code here
Test cases

Case 1

Case 2

Case 3

Input

tree = [5, 8, 1, -1, 3, -1, -1, -1, -1, 6]

Expected

4