KatInterview

Longest Path Between Any Two Nodes in an Indexed Binary Tree

Trees & GraphsAuto-graded · 19 test cases
MediumAuto-gradedTrees & Graphsbinary-treedfsbfs

Last 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 -1 or 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.