Skip to content
BytePatterns

Widest Node To Node Path

MediumTrees & BST#dfs#post-order~30m

Problem

In a binary tree, measure the longest path between any two nodes, counting the links along it rather than the nodes. The path does not have to pass through the root, and it may bend at exactly one node on the way. Return 0 for an empty tree or a tree with a single node.

Examples

Input:  tree = 1 with left child 2 having children 4 and 5, and right child 3
Output: 3
Why:    the path 4, 2, 1, 3 uses three links and bends at the root
Input:  tree = 1 with a single left child 2
Output: 1
Why:    a single link is the only path there is
Input:  tree = empty
Output: 0
Why:    edge case, there is no path to measure

Hints

0 / 3

Stuck on the idea rather than the code? Diameter of a Tree covers it.