What is Tree Diameter
The diameter is the longest path between any two nodes, counted in edges. The path does not have to pass through the root. It can bend through any node.
1 2 3 4 5 longest path has 3 edges
Approach
At each node, the longest path that bends there is the height of the left child plus the height of the right child. Keep the best bend while the heights are computed.
The picture labels the height returned by each node and remembers the best bend. A single node has diameter 0.
Interactive solution
The finished tree is on screen when the page opens. Next and Play start again from the first step. The play controls sit under the tree and the pseudocode.
Complexity
| Piece | Cost | Why |
|---|---|---|
| Time | O(n) | Each node contributes one bend. |
| Call stack | O(h) | Heights are computed by recursion. |
Implementation
def solve(self, root):
best = [0]
def height(node):
if not node:
return 0
left, right = height(node.left), height(node.right)
best[0] = max(best[0], left + right)
return 1 + max(left, right)
height(root)
return best[0]