15% off all plans & roadmaps Use code

See plans

Diameter of Binary Tree

Updated

TL;DR: Find the longest path, counted in edges, between any two nodes of a binary tree. Compute each node's height bottom-up and, at every node, test left height plus right height against a running maximum.

Problem

Given the root of a binary tree, return the length of the tree's diameter.

The diameter is the length of the longest path between any two nodes in the tree. The path may or may not pass through root. The length of a path is the number of edges on it, not the number of nodes.

Example 1

Input: root = [1,2,3,4,5]
Output: 3
Explanation: The longest path is [4,2,1,3] or [5,2,1,3], which has 3 edges.

Example 2

Input: root = [1,2]
Output: 1

Constraints

  • The number of nodes in the tree is in the range [1, 10^4].
  • -100 <= Node.val <= 100

Constraints that matter

  • n is at most 10^4, so an O(n^2) solution does about 5 * 10^7 steps on a chain. It passes in compiled languages but it is the wrong answer to give in an interview.
  • The answer counts edges, not nodes. A path with k nodes has k - 1 edges, so the arithmetic must match that definition.
  • The tree has at least one node, but a single node is a valid input and its diameter is 0.
  • A chain of 10^4 nodes means recursion depth 10^4. Python's default recursion limit is about 1000, so the code on this page uses an explicit stack to stay safe.
  • Node values range from -100 to 100 but never matter. Only the shape of the tree decides the answer.

View on LeetCode

Hints

Hint 1

This is a recursive postorder traversal problem.

Hint 2

Use the definition directly.

Solution

Intuition

This is a recursive postorder traversal problem. The answer for a node depends on facts about its two children, so you want to finish the children first and then combine.

Picture a company where each manager asks the two people below for their depth, writes down the sum of those two answers as a candidate, and then reports their own depth upward. The height map is the stack of written reports, and walking the order backwards is how the bottom-most managers get to speak first.

Look at any path in a tree. It has exactly one highest node, the one closest to the root. The path goes down from that node into its left subtree, down into its right subtree, or both. So the longest path whose highest node is u has length height(u.left) + height(u.right), where an empty child has height 0 and a leaf has height 1.

That gives a full plan. Visit every node, treat it as the highest point of a path, compute that path's length, and keep the maximum. The diameter does not have to touch the root, so you must check every node and not only the top one.

The cost question is how you get the heights. Asking for a fresh height at every node repeats work, because a node's height is recomputed once for each ancestor. Postorder removes the repeat. Each node computes its height once from the heights its children already produced, and it uses those same two numbers to test the diameter.

Watch the pattern animation

Worked example

Input: root = [1, null, 2, null, 3, null, 4]
Output: 3
Explanation: Every node has only a right child, so the tree is a chain 1 -> 2 -> 3 -> 4. The longest path runs from node 1 to node 4 and uses 3 edges.

Approach 1: Brute force: height at every node

Use the definition directly. For every node, measure the height of its left subtree and the height of its right subtree with a separate helper. Add them, and keep the largest sum across all nodes.

This is correct because every path has a highest node, and that node's two heights give the longest path through it. It is slow for a reason covered next.

Steps

  1. Set best = 0 and put the root on a stack to visit every node.
  2. Pop a node and call the depth helper on its left child and on its right child.
  3. Add the two depths and update best if the sum is larger.
  4. Push the node's non-null children onto the stack.
  5. Repeat until the stack is empty, then return best.
  6. The depth helper walks the subtree level by level and counts the levels. An empty subtree has depth 0.

Dry run

Tree: the chain 1 -> 2 -> 3 -> 4, all right children.

  • Node 1: left depth 0, right depth 3 (nodes 2, 3, 4). Sum 3, so best = 3.
  • Node 2: left depth 0, right depth 2. Sum 2, best stays 3.
  • Node 3: left depth 0, right depth 1. Sum 1.
  • Node 4: both depths 0. Sum 0.

The stack is empty and the result is 3. Notice that the helper walked 3 nodes for node 1, then 2 for node 2, then 1 for node 3. That shrinking-but-repeated walking is the waste.

Complexity

TimeO(n^2)
SpaceO(n)

Here n is the number of nodes. The outer traversal visits each node once. For each node the helper walks that node's whole subtree.

On a chain, the node at position k has n - k nodes below it, so the total is about n^2 / 2, which is O(n^2). The stack and the level queue each hold at most n nodes, so space is O(n).

PythonTested in our runner

from typing import List, Optional

class Solution:
    def diameterOfBinaryTree(self, root: Optional[TreeNode]) -> int:
        # Depth of a subtree, counted in nodes, by walking it level by level.
        def depth(node):
            levels = 0
            level = [node] if node else []
            while level:
                levels += 1
                nxt = []
                for cur in level:
                    if cur.left:
                        nxt.append(cur.left)
                    if cur.right:
                        nxt.append(cur.right)
                level = nxt
            return levels

        best = 0
        stack = [root] if root else []
        while stack:
            node = stack.pop()
            # Longest path whose highest node is this node.
            best = max(best, depth(node.left) + depth(node.right))
            if node.left:
                stack.append(node.left)
            if node.right:
                stack.append(node.right)
        return best
Recursive Postorder Traversal pattern infographic for Diameter of Binary Tree

Solution pattern

Recursive Postorder Traversal

Part of Tree Traversal Patterns (DFS & BFS)

Approach 2: One-pass postorder DFSOptimalRecursive Postorder Traversal

What's slow: the brute force recomputes the height of the same subtree once for every ancestor. In the chain, node 4's depth is measured by nodes 1, 2 and 3 separately.

The insight that fixes it: a node's height is 1 + max(left height, right height). If you process children before parents, each height is computed once, from two numbers you already hold. At the same moment you have both child heights, so the diameter candidate left + right costs one addition.

The usual code does this with recursion that returns the height and updates a shared maximum. This page uses an explicit stack instead, which is the same postorder idea. A chain of 10^4 nodes would overflow Python's default recursion limit, so the iterative form is safer.

You collect nodes in a preorder-style order, then walk that list backwards. In the reversed list every child appears before its parent.

Why it is correct. Every path has exactly one highest node, and its length is the height of that node's left child plus the height of its right child, with empty children counting as 0. Reversing the preorder list guarantees that when a node is processed, both of its children already have final heights stored in the map. So each node is tested as the top of its best path, and since every node is checked, no path can be missed.

Steps

  1. If root is null, return 0. Otherwise set best = 0 and create an empty height map.
  2. Walk the tree with a stack. Pop a node, append it to order, then push its non-null children.
  3. Process order from the last entry to the first, so children come before parents.
  4. For each node, read left and right from the map. A missing child counts as 0.
  5. Update best = max(best, left + right).
  6. Store height[node] = 1 + max(left, right) for its parent to read.
  7. After the loop, return best.

Dry run

Tree: the chain 1 -> 2 -> 3 -> 4. The stack walk produces order = [1, 2, 3, 4]. Processing runs from the back.

StepNodeleft hright hleft + rightbestheight stored
140000height[4] = 1
230111height[3] = 2
320222height[2] = 3
410333height[1] = 4

After step 4 the loop ends and the function returns best = 3, which matches the expected output. Each node was touched once, and no height was measured twice.

Complexity

TimeO(n)
SpaceO(n)

Here n is the number of nodes. The stack walk pops and pushes each node once. The backward pass handles each node once with a constant number of map reads, one comparison, and one map write.

That is about 2n node visits, so time is O(n). The order list and the height map each hold n entries, and the stack never holds more than n, so space is O(n). A recursive version would use O(h) stack for tree height h and no list or map, but h can reach n on a chain.

PythonTested in our runner

from typing import List, Optional

class Solution:
    def diameterOfBinaryTree(self, root: Optional[TreeNode]) -> int:
        if not root:
            return 0

        # Collect nodes so that every parent appears before its children.
        order = []
        stack = [root]
        while stack:
            node = stack.pop()
            order.append(node)
            if node.left:
                stack.append(node.left)
            if node.right:
                stack.append(node.right)

        height = {}
        best = 0
        # Walking backwards means children are finished before parents.
        for node in reversed(order):
            left = height.get(node.left, 0)
            right = height.get(node.right, 0)
            best = max(best, left + right)
            height[node] = 1 + max(left, right)
        return best

Common mistakes

  • Returning the diameter from the helper instead of the height. The parent needs a height to build its own path, so the helper must return 1 + max(left, right) and keep the diameter in a separate variable.
  • Computing only height(root.left) + height(root.right) at the top. The longest path can sit entirely inside a subtree, so you must update best at every node.
  • Counting nodes instead of edges, for example best = left + right + 1. The problem counts edges, so the candidate is left + right when a null child has height 0.
  • Giving a null child height 1, or a leaf height 0. Pick one convention and keep it. With null as 0 and leaf as 1, left + right is already the edge count.
  • Declaring best as a local inside the recursive helper in Python or Java. Each call gets its own copy, so updates are lost. Use nonlocal, an instance field, or the explicit-stack form with a single local.
  • Writing a plain recursive solution in Python for a 10^4 chain without raising the recursion limit. It crashes with RecursionError. Use an explicit stack, or call sys.setrecursionlimit with care.

Edge cases

  • A single node, [1]: both child heights are 0, so the answer is 0.
  • Two nodes, [1,2]: the root has left height 1 and right height 0, so the answer is 1.
  • A chain of 10^4 nodes: the answer is 9999, and recursion depth reaches 10^4, which breaks the default Python recursion limit.
  • The longest path avoids the root: a root with a tiny right child and a left subtree that is wide and deep. The answer comes from a node inside the left subtree.
  • A perfectly balanced tree such as [1,2,3,4,5,6,7]: the longest path goes leaf, parent, root, parent, leaf, so the answer is 4.
  • Negative or repeated values: [-100,-100,-100] gives 2, because values never affect the shape.

Follow-ups interviewers ask

How would you return the actual path and not only its length?
Store, alongside best, the node where the best value was found. Then walk down from that node, following the child with the larger height on each side. Joining the left walk, the node, and the right walk gives the path. This adds O(n) time and no extra asymptotic space.
How does the solution change for an n-ary tree?
A node can have many children, so keep the two largest child heights. The candidate at a node is the sum of those two, and the height returned is 1 plus the largest. Time stays O(n) because you look at each child once.
Can you reduce the extra space to O(h), where h is the tree height?
Yes, with the recursive version. The helper returns the height, a single shared variable holds best, and the only extra memory is the call stack, which is O(h). That is O(log n) for a balanced tree and O(n) for a chain. Say aloud that the recursion limit matters in Python.

Diameter of Binary Tree FAQ

What is the time complexity of Diameter of Binary Tree?

The one-pass postorder solution runs in O(n) time, where n is the number of nodes, because it handles each node a constant number of times. The brute force that recomputes depth at every node is O(n^2) on a chain.

Why use postorder DFS for Diameter of Binary Tree?

A node's height and its diameter candidate both depend on its children's heights. Postorder finishes the children first, so each node reads two ready numbers, updates the best answer, and passes up its own height. Every height is computed once.

Does the diameter of a binary tree have to pass through the root?

No. The longest path can lie entirely inside the left or right subtree. That is why the solution checks left + right at every node and keeps a running maximum instead of testing only the root.

Why does Diameter of Binary Tree count edges and not nodes?

The problem defines path length as the number of edges. A path through k nodes has k - 1 edges. With null children at height 0 and leaves at height 1, left + right gives the edge count with no adjustment.

Can Diameter of Binary Tree be solved in O(1) extra space?

Not with the standard approach. You must remember child heights until the parent is processed, which needs a stack or call stack of size O(h). The recursive version uses O(h) and the version on this page uses O(n). Claiming O(1) would require modifying the tree, which is not worth the complexity here.

Why does my Python solution for Diameter of Binary Tree hit a recursion error?

Python allows about 1000 nested calls by default, and a chain of 10^4 nodes needs that many. Either raise the limit with sys.setrecursionlimit or use an explicit stack, as the code on this page does.

Asked at

See which companies ask this — Pro

Practise it