InferenceAI

Enter at least two characters to search.

Start free

Tree Diameter

mediumTrees25 min25 XP

Return the diameter of the binary tree: the number of edges on the longest path between any two nodes. The path doesn't have to pass through the root.

Trees are given in level order as a list, with None for a missing child (for example [3, 9, 20, None, None, 15, 7]).

Examples

EXAMPLE WALKTHROUGHthrough the root

A guided view of the published example, not a trace of your code.

INPUT[[1,2,3,4,5]]
TASKtree_diameter()
EXPECTED OUTPUT3

Start with the input values shown in this example.

Example 1 of 3

Input: values = [1,2,3,4,5]

Output: 3

Explanation: through the root

Input: values = [1,2]

Output: 1

Explanation: two nodes

Input: values = []

Output: 0

Explanation: empty

Hint 1

For each node, the longest path through it is height(left) + height(right).

Hint 2

Compute heights bottom-up and track the best sum.

Topics

DSATreesPython