15% off all plans & roadmaps Use code
See plansDiameter of Binary Tree
- LeetCode 543
- Easy
- Tree Traversal Patterns (DFS & BFS)
- Recursive Postorder Traversal
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.
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.
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
- Set
best = 0and put the root on a stack to visit every node. - Pop a node and call the depth helper on its left child and on its right child.
- Add the two depths and update
bestif the sum is larger. - Push the node's non-null children onto the stack.
- Repeat until the stack is empty, then return
best. - 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,
beststays 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
| Time | O(n^2) |
|---|---|
| Space | O(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
JavaTested in our runner
import java.util.*;
class Solution {
public int diameterOfBinaryTree(TreeNode root) {
if (root == null) return 0;
int best = 0;
Deque<TreeNode> stack = new ArrayDeque<>();
stack.push(root);
while (!stack.isEmpty()) {
TreeNode node = stack.pop();
// Longest path whose highest node is this node.
best = Math.max(best, depth(node.left) + depth(node.right));
if (node.left != null) stack.push(node.left);
if (node.right != null) stack.push(node.right);
}
return best;
}
// Depth in nodes, found by walking the subtree level by level.
private int depth(TreeNode node) {
if (node == null) return 0;
int levels = 0;
Deque<TreeNode> queue = new ArrayDeque<>();
queue.add(node);
while (!queue.isEmpty()) {
levels++;
for (int i = queue.size(); i > 0; i--) {
TreeNode cur = queue.poll();
if (cur.left != null) queue.add(cur.left);
if (cur.right != null) queue.add(cur.right);
}
}
return levels;
}
}
C++Tested in our runner
#include <vector>
#include <queue>
#include <algorithm>
class Solution {
public:
int diameterOfBinaryTree(TreeNode* root) {
if (!root) return 0;
int best = 0;
std::vector<TreeNode*> stack{root};
while (!stack.empty()) {
TreeNode* node = stack.back();
stack.pop_back();
// Longest path whose highest node is this node.
best = std::max(best, depth(node->left) + depth(node->right));
if (node->left) stack.push_back(node->left);
if (node->right) stack.push_back(node->right);
}
return best;
}
private:
// Depth in nodes, found by walking the subtree level by level.
int depth(TreeNode* node) {
if (!node) return 0;
int levels = 0;
std::queue<TreeNode*> q;
q.push(node);
while (!q.empty()) {
levels++;
for (int i = (int)q.size(); i > 0; --i) {
TreeNode* cur = q.front();
q.pop();
if (cur->left) q.push(cur->left);
if (cur->right) q.push(cur->right);
}
}
return levels;
}
};
JavaScriptTested in our runner
/**
* @param {TreeNode} root
* @return {number}
*/
var diameterOfBinaryTree = function(root) {
// Depth in nodes, found by walking the subtree level by level.
const depth = (node) => {
let levels = 0;
let level = node ? [node] : [];
while (level.length > 0) {
levels++;
const next = [];
for (const cur of level) {
if (cur.left) next.push(cur.left);
if (cur.right) next.push(cur.right);
}
level = next;
}
return levels;
};
let best = 0;
const stack = root ? [root] : [];
while (stack.length > 0) {
const node = stack.pop();
// Longest path whose highest node is this node.
best = Math.max(best, depth(node.left) + depth(node.right));
if (node.left) stack.push(node.left);
if (node.right) stack.push(node.right);
}
return best;
};
GoTested in our runner
// Depth in nodes, found by walking the subtree level by level.
func depth(node *TreeNode) int {
if node == nil {
return 0
}
levels := 0
level := []*TreeNode{node}
for len(level) > 0 {
levels++
var next []*TreeNode
for _, cur := range level {
if cur.Left != nil {
next = append(next, cur.Left)
}
if cur.Right != nil {
next = append(next, cur.Right)
}
}
level = next
}
return levels
}
func diameterOfBinaryTree(root *TreeNode) int {
if root == nil {
return 0
}
best := 0
stack := []*TreeNode{root}
for len(stack) > 0 {
node := stack[len(stack)-1]
stack = stack[:len(stack)-1]
// Longest path whose highest node is this node.
d := depth(node.Left) + depth(node.Right)
if d > best {
best = d
}
if node.Left != nil {
stack = append(stack, node.Left)
}
if node.Right != nil {
stack = append(stack, node.Right)
}
}
return best
}
C#Tested in our runner
public class Solution {
public int diameterOfBinaryTree(TreeNode root) {
if (root == null) return 0;
int best = 0;
var stack = new Stack<TreeNode>();
stack.Push(root);
while (stack.Count > 0) {
TreeNode node = stack.Pop();
// Longest path whose highest node is this node.
best = Math.Max(best, Depth(node.left) + Depth(node.right));
if (node.left != null) stack.Push(node.left);
if (node.right != null) stack.Push(node.right);
}
return best;
}
// Depth in nodes, found by walking the subtree level by level.
private int Depth(TreeNode node) {
if (node == null) return 0;
int levels = 0;
var queue = new Queue<TreeNode>();
queue.Enqueue(node);
while (queue.Count > 0) {
levels++;
for (int i = queue.Count; i > 0; i--) {
TreeNode cur = queue.Dequeue();
if (cur.left != null) queue.Enqueue(cur.left);
if (cur.right != null) queue.Enqueue(cur.right);
}
}
return levels;
}
}

Solution pattern
Recursive Postorder Traversal
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
- If
rootis null, return 0. Otherwise setbest = 0and create an emptyheightmap. - Walk the tree with a stack. Pop a node, append it to
order, then push its non-null children. - Process
orderfrom the last entry to the first, so children come before parents. - For each node, read
leftandrightfrom the map. A missing child counts as 0. - Update
best = max(best, left + right). - Store
height[node] = 1 + max(left, right)for its parent to read. - 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.
| Step | Node | left h | right h | left + right | best | height stored |
|---|---|---|---|---|---|---|
| 1 | 4 | 0 | 0 | 0 | 0 | height[4] = 1 |
| 2 | 3 | 0 | 1 | 1 | 1 | height[3] = 2 |
| 3 | 2 | 0 | 2 | 2 | 2 | height[2] = 3 |
| 4 | 1 | 0 | 3 | 3 | 3 | height[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
| Time | O(n) |
|---|---|
| Space | O(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
JavaTested in our runner
import java.util.*;
class Solution {
public int diameterOfBinaryTree(TreeNode root) {
if (root == null) return 0;
// Collect nodes so that every parent appears before its children.
List<TreeNode> order = new ArrayList<>();
Deque<TreeNode> stack = new ArrayDeque<>();
stack.push(root);
while (!stack.isEmpty()) {
TreeNode node = stack.pop();
order.add(node);
if (node.left != null) stack.push(node.left);
if (node.right != null) stack.push(node.right);
}
Map<TreeNode, Integer> height = new HashMap<>();
int best = 0;
// Walking backwards means children are finished before parents.
for (int i = order.size() - 1; i >= 0; i--) {
TreeNode node = order.get(i);
int left = node.left == null ? 0 : height.get(node.left);
int right = node.right == null ? 0 : height.get(node.right);
best = Math.max(best, left + right);
height.put(node, 1 + Math.max(left, right));
}
return best;
}
}
C++Tested in our runner
#include <vector>
#include <unordered_map>
#include <algorithm>
class Solution {
public:
int diameterOfBinaryTree(TreeNode* root) {
if (!root) return 0;
// Collect nodes so that every parent appears before its children.
std::vector<TreeNode*> order;
std::vector<TreeNode*> stack{root};
while (!stack.empty()) {
TreeNode* node = stack.back();
stack.pop_back();
order.push_back(node);
if (node->left) stack.push_back(node->left);
if (node->right) stack.push_back(node->right);
}
std::unordered_map<TreeNode*, int> height;
int best = 0;
// Walking backwards means children are finished before parents.
for (int i = (int)order.size() - 1; i >= 0; --i) {
TreeNode* node = order[i];
int left = node->left ? height[node->left] : 0;
int right = node->right ? height[node->right] : 0;
best = std::max(best, left + right);
height[node] = 1 + std::max(left, right);
}
return best;
}
};
JavaScriptTested in our runner
/**
* @param {TreeNode} root
* @return {number}
*/
var diameterOfBinaryTree = function(root) {
if (!root) return 0;
// Collect nodes so that every parent appears before its children.
const order = [];
const stack = [root];
while (stack.length > 0) {
const node = stack.pop();
order.push(node);
if (node.left) stack.push(node.left);
if (node.right) stack.push(node.right);
}
const height = new Map();
let best = 0;
// Walking backwards means children are finished before parents.
for (let i = order.length - 1; i >= 0; i--) {
const node = order[i];
const left = node.left ? height.get(node.left) : 0;
const right = node.right ? height.get(node.right) : 0;
best = Math.max(best, left + right);
height.set(node, 1 + Math.max(left, right));
}
return best;
};
GoTested in our runner
func diameterOfBinaryTree(root *TreeNode) int {
if root == nil {
return 0
}
// Collect nodes so that every parent appears before its children.
order := []*TreeNode{}
stack := []*TreeNode{root}
for len(stack) > 0 {
node := stack[len(stack)-1]
stack = stack[:len(stack)-1]
order = append(order, node)
if node.Left != nil {
stack = append(stack, node.Left)
}
if node.Right != nil {
stack = append(stack, node.Right)
}
}
height := make(map[*TreeNode]int)
best := 0
// Walking backwards means children are finished before parents.
for i := len(order) - 1; i >= 0; i-- {
node := order[i]
left, right := 0, 0
if node.Left != nil {
left = height[node.Left]
}
if node.Right != nil {
right = height[node.Right]
}
if left+right > best {
best = left + right
}
if left > right {
height[node] = 1 + left
} else {
height[node] = 1 + right
}
}
return best
}
C#Tested in our runner
public class Solution {
public int diameterOfBinaryTree(TreeNode root) {
if (root == null) return 0;
// Collect nodes so that every parent appears before its children.
var order = new List<TreeNode>();
var stack = new Stack<TreeNode>();
stack.Push(root);
while (stack.Count > 0) {
TreeNode node = stack.Pop();
order.Add(node);
if (node.left != null) stack.Push(node.left);
if (node.right != null) stack.Push(node.right);
}
var height = new Dictionary<TreeNode, int>();
int best = 0;
// Walking backwards means children are finished before parents.
for (int i = order.Count - 1; i >= 0; i--) {
TreeNode node = order[i];
int left = node.left == null ? 0 : height[node.left];
int right = node.right == null ? 0 : height[node.right];
best = Math.Max(best, left + right);
height[node] = 1 + Math.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 updatebestat every node. - Counting nodes instead of edges, for example
best = left + right + 1. The problem counts edges, so the candidate isleft + rightwhen 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 + rightis already the edge count. - Declaring
bestas a local inside the recursive helper in Python or Java. Each call gets its own copy, so updates are lost. Usenonlocal, 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 callsys.setrecursionlimitwith 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
Related problems
- Balanced Binary Tree · same technique: Recursive Postorder Traversal
- Maximum Depth of Binary Tree · same technique: Recursive Postorder Traversal
- Binary Tree Postorder Traversal · same technique: Recursive Postorder Traversal
- House Robber III · same technique: Recursive Postorder Traversal
- Delete Leaves With a Given Value · same technique: Recursive Postorder Traversal
- Same Tree · same pattern: Tree Traversal Patterns (DFS & BFS)
- Invert Binary Tree · same pattern: Tree Traversal Patterns (DFS & BFS)
- Subtree of Another Tree · same pattern: Tree Traversal Patterns (DFS & BFS)
- Binary Tree Inorder Traversal · same pattern: Tree Traversal Patterns (DFS & BFS)
- Binary Tree Preorder Traversal · same pattern: Tree Traversal Patterns (DFS & BFS)