Graph Theory37 sections · 1633 units
Open in Course

LeetCode 543 Diameter of Binary Tree - Algorithm

Recursive DFS

1.1. Base case: if node is null, return height 00.

2.2. Recursively compute left height and right height.

3.3. Diameter through this node = left height + right height. Update global max.

4.4. Return 11 + max(left height, right height) as this node's height.

Time: O(n)O(n), visiting each node once. Space: O(h)O(h) for recursion stack where hh is height. The recursion naturally handles the tree structure.