Editor

Diameter of a Tree

#127 · Trees · Advanced · 120 XP · about 20 min

The diameter of a binary tree is the number of edges on the longest path between any two nodes, where a path follows parent-child links and never visits a node twice. The path does not have to pass through the root. Write diameter(root) that returns it. A tree with no nodes or a single node has diameter 0.

Each node is a Node with a value val and two children, left and right, which are None when missing. The provided build makes a tree from a list of values in level order, where None marks a missing child.

Examples

      6
     / \
    3   9
   / \
  1   4
diameter(build([6, 3, 9, 1, 4]))  # returns 3
diameter(build([5, 8]))  # returns 1
diameter(build([7]))  # returns 0

The drawing shows the first tree. Its longest paths, 1, 3, 6, 9 and 4, 3, 6, 9, each have 3 edges.

Constraints

  • 0 to 2,000 nodes.

Note

  • The longest path can stay entirely inside one subtree, away from the root.

Ready?

Accept the challenge to start writing. A small timer counts the time this page is in view.

Output appears here.