Data Structures19 sections · 729 units
Open in Course

Diameter Solution

Track max during DFS

The diameter through a node is leftHeight + rightHeight. Track the maximum across all nodes:

function diameterOfBinaryTree(root):
    diameter = 0

    function height(node):
        if node == null:
            return 0
        leftH = height(node.left)
        rightH = height(node.right)
        diameter = max(diameter, leftH + rightH)
        return 1 + max(leftH, rightH)

    height(root)
    return diameter

Notice: compute height recursively, but track the maximum diameter as a side effect. The diameter at each node is the sum of its children's heights.

Time: O(n)O(n). Space: O(h)O(h).