Graph Theory37 sections · 1633 units
Open in Course

LeetCode 543 Diameter of Binary Tree - Implementation

Python solution

Here is the solution:

diameter = 0

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

function diameterOfBinaryTree(root):
    height(root)
    return diameter

Clean and simple. The diameter is tracked in a global variable.

This runs in O(n)O(n) time and uses O(h)O(h) space where hh is tree height.