Binary Tree

Tree Diameter Visualizer

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.

Height in edges to a leafA missing child has height 0. A node's height, in edges, is one more than the taller child. A leaf has height 1 in this count because the edge up to its parent is what the parent adds.
The bendLeft height plus right height is the number of edges on the path that goes down both sides of this node. The diameter is the largest bend in the tree.

The picture labels the height returned by each node and remembers the best bend. A single node has diameter 0.

Interactive solution

The best bend, measured in edges
best = 0
def height(node):
if node is null: return 0
left = height(node.left)
right = height(node.right)
best = max(best, left + right)
return 1 + max(left, right)
Step 0/0 Answer —

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

PieceCostWhy
TimeO(n)Each node contributes one bend.
Call stackO(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]