Longest Path Between Any Two Nodes in an Indexed Binary Tree
Trees & GraphsAuto-graded · 19 test casesLast updated
Find the longest path, counted in edges, between any two nodes of a binary tree stored as a child-index list, testing tree height computation and avoiding deep recursion.
Longest Path in a Binary Tree
A binary tree is stored as a list of child-index pairs. Entry tree[i] = [left, right] holds the indices of the left and right children of node i. A value of -1 means that child does not exist. Node 0 is always the root.
Return the length of the longest simple path between any two nodes of the tree. Length is measured in edges, not nodes. The path may or may not pass through the root, and it can start and end at any nodes.
If tree is empty, return 0. A tree with a single node also has answer 0.
Input
tree: a list of[left, right]pairs of integers, where each value is either a valid node index or-1.
Output
- An integer: the number of edges on the longest path between any two nodes.
Constraints
0 <= len(tree) <= 10^4- Each pair
tree[i]has exactly two integers, each either-1or a valid index in[0, len(tree) - 1]. - The input describes a valid binary tree rooted at node
0: every non-root node has exactly one parent and all nodes are reachable from the root. - The tree may be very deep (for example, a chain of 10^4 nodes), so be careful with recursion limits.
Examples
Example 1
Input: longest_path_in_tree([[1, 2], [3, 4], [-1, -1], [-1, -1], [-1, -1]])
Output: 3
Example 2
Input: longest_path_in_tree([[1, -1], [-1, -1]])
Output: 1
Example 3
Input: longest_path_in_tree([[1, 2], [-1, -1], [-1, -1]])
Output: 2
Hints
Hint 1
Every path has a single highest node. For that node, the best path goes down its deepest left branch and its deepest right branch.
Hint 2
If you define a subtree's height as the number of nodes on its longest downward path (missing child = 0), then the best path through a node has height(left) + height(right) edges.
Hint 3
The answer is the maximum of that quantity over all nodes, not just the root. To avoid deep recursion, get an order where parents come before children (such as BFS) and process it in reverse.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Every path in a tree has exactly one highest node (its apex). For a given apex v, the longest path with that apex goes down the deepest branch on the left and the deepest branch on the right.
Define height(v) as the number of nodes on the longest downward path starting at v, with a missing child having height 0 and a leaf height 1. Each child then contributes exactly height(child) edges to the path (the edge from v to the child plus the edges below it). So the best path with apex v has
height(left) + height(right)
edges. The answer is the maximum of this value over all nodes.
To avoid Python's recursion limit on chains of up to 10^4 nodes, do it iteratively:
- Run a BFS from node
0to record an order in which each parent comes before its children. - Walk that order in reverse, so children are handled before parents. For each node compute its height and update the best diameter.
Why it is correct
- Every path has a unique apex, so every path is considered when its apex is processed.
- The two halves of a path through an apex lie in disjoint subtrees, so each can be maximized independently, and each maximum is that child's height.
- Taking the maximum over all nodes covers paths that avoid the root.
- An empty tree returns
0early, and a single node gives0 + 0 = 0.
Complexity
- Time: O(n), each node is visited twice at most.
- Space: O(n) for the order list and heights.
Reference solution
from typing import List
def longest_path_in_tree(tree: List[List[int]]) -> int:
if not tree:
return 0
heights = [0] * len(tree)
order = [0]
for node in order:
left, right = tree[node]
if left != -1:
order.append(left)
if right != -1:
order.append(right)
best = 0
for node in reversed(order):
left, right = tree[node]
left_h = heights[left] if left != -1 else 0
right_h = heights[right] if right != -1 else 0
heights[node] = 1 + max(left_h, right_h)
best = max(best, left_h + right_h)
return best