Longest path between any two nodes

Trees Mid-level Python 3.13+ Reviewed By Best Latest Apps

Pick the fix

Why can a simple 'height(left) + height(right) at the root' be wrong?

Options

Choose an answer, then open Show answer below to check it.

Show answer

Answer: A The longest path can bend at a node deep in one subtree

Right: a lopsided tree can hide its longest path entirely on one side.

Checking every node as a possible bend point is what finds the path, and the bottom-up walk does it in one pass.

Why not the others?
  • B Heights must be counted in nodes. Edges versus nodes changes the number, not where the path is.
  • C The root always lies on the longest path. That is exactly the false assumption.

30-second answer

For each node, the longest path that bends at that node is height(left) + height(right) in edges. Compute heights bottom-up and keep the best bend seen in an outer variable. One post-order walk: O(n) time, O(h) stack.

Practise saying it · 60 s. No recording, just a timer

Explain the longest-path-between-nodes recursion.

Say your answer out loud, then check which of these points you covered:

  • Height returned
  • Best bend recorded
  • O(n)

Deep dive

The function returns one thing (height) but records another (best path): a common tree pattern.

Calling a separate height function at every node is O(n²) on a chain.

Count edges, not nodes, unless the question says otherwise.

Python solution Ran on Python 3.13.5 · mypy --strict
Python 3.13
def longest_path(root: Node | None) -> int:
    best = 0

    def height(node: Node | None) -> int:
        nonlocal best
        if node is None:
            return 0
        left, right = height(node.left), height(node.right)
        best = max(best, left + right)
        return 1 + max(left, right)
    height(root)
    return best

Common mistakes

  • Assuming the longest path passes through the root.
  • Mixing node counts and edge counts between the height and the answer.

Senior take & follow-ups

Say 'return height, record the best bend' before writing. It shows you know the pattern, not just this answer.

Follow-up questions

Think of your answer first, then open the hint.

  1. What if nodes have weights?

    Show hint

    Track the heaviest downward path instead of height; same structure.

  2. How would you find the path in a general tree?

    Show hint

    Two BFS passes: farthest node from any node, then farthest from that.

What each operation costs: Binary Tree · Binary Search Tree · Tree Traversal

From the author

DSA Master - Data & Algorithms

Free on iPhone and iPad: watch 50+ data structures and algorithms step through animations, run the code in the playground, and try the daily challenge.

Suggest a fix if something here is wrong or out of date.