Menu
CoddyTech

Diameter 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 diameter of the tree: the number of edges on the longest path between any two nodes. The path may pass through the root or stay inside one subtree.

Function

diameterOfBinaryTree(tree: integer-array) → integer
treeinteger-array
the binary tree in level order, with -1 for an empty spot
Returnsinteger
the number of edges on the longest path between two nodes

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 = [8, 3, 6, 1, 4, -1, -1, -1, -1, 7]
Output
4
Explanation
The path 7, 4, 3, 8, 6 (indexes 9, 4, 1, 0, 2) holds five nodes joined by four edges. It turns at the root: three edges down the left side and one down the right.

lock icon+12 hidden tests on Submit

challenge icon

Follow-up

How would you return the path itself, the node values from one end of the diameter to the other?

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

Case 1

Case 2

Case 3

Input

tree = [8, 3, 6, 1, 4, -1, -1, -1, -1, 7]

Expected

4