Diameter of N-ary Tree solution explained
To find the diameter of an N-ary tree, do one post-order pass where every node reports its height, and at each node add the two largest values of child height plus one. The biggest such sum anywhere in the tree is the diameter, measured in edges. Each node and edge is handled once, so it runs in O(n) time with O(h) extra space.
By Evin JohnPublished 9 min read
What the problem asks
You get the root of a tree in which each node holds a list of children, and that list can be empty, short or very long. A path is any sequence of nodes joined by edges, with no node repeated, and it may go up toward a common ancestor and back down. The diameter is the length of the longest such path, counted as the number of edges on it. Return that number.
Tree P Tree Q
1 10
/ | \ |
2 3 4 20
| / \ / \
5 7 8 30 40
| | | |
6 9 50 70
| |
60 80
Tree P: 6-5-2-1-4-8-9 has 6 edges, answer 6
Tree Q: 60-50-30-20-40-70-80 has 6 edges, answer 6Tree Q is the one to keep in mind. Its root has a single child, so the deepest path from the root is only 4 edges long, yet the longest path in the tree is 6 edges and never touches the root. A solution that only measures from the root fails here. Two smaller facts: a tree with one node has diameter 0, and a star (a root with many leaf children) has diameter 2, because the best path runs leaf, root, leaf.
Why interviewers like it
It is the binary-tree diameter with the left and right slots replaced by a list, so it checks whether you understood the binary version or memorized it. Someone who memorized "left height plus right height" has to stop and think about which two children to use. Someone who understood it says "the two tallest children" right away and keeps going. The interviewer also watches whether you separate the value a node returns (its height) from the value you are maximizing (a path through it). Common follow-ups:
- Return the path, not just its length. Remember which child produced each node's height, then rebuild both arms from the node where the best bend happened.
- Weighted edges. Each edge has a positive length. Return the heaviest path. The same pass works with weights added instead of one.
- The tree arrives as an edge list. Now nothing is rooted. Either pick any node as the root and build child lists, or use the two-search trick described below.
- Very deep trees. A chain of a hundred thousand nodes breaks naive recursion. Show the iterative version or say how you would get one.
Brute force: measure from every node
The diameter is the largest distance between any two nodes, so the literal approach is to compute every distance. Treat the tree as an undirected graph (parent and child edges both ways), run a breadth-first search from each node, and keep the largest distance any search reaches. Each search is O(n) and there are n of them, so the total is O(n²). It is slow on big trees but short, obviously correct, and the version we used as the test reference.
from collections import deque
class Node:
def __init__(self, val=None, children=None):
self.val = val
self.children = children if children is not None else []
def diameter_all_pairs(root):
if root is None:
return 0
adj = {}
todo = [root]
while todo:
node = todo.pop()
adj.setdefault(node, [])
for child in node.children:
adj[node].append(child)
adj.setdefault(child, []).append(node)
todo.append(child)
best = 0
for start in adj:
dist = {start: 0}
queue = deque([start])
while queue:
cur = queue.popleft()
for nxt in adj[cur]:
if nxt not in dist:
dist[nxt] = dist[cur] + 1
queue.append(nxt)
best = max(best, max(dist.values()))
return bestThe O(n) idea: every path has a highest node
Pick any path in a rooted tree and look at the node on it closest to the root. Call it the bend. From the bend, the path goes down into at most two different children, one arm each. So the longest path that bends at a node is its tallest arm plus its second tallest arm, where an arm through child c has length height(c) + 1. A leaf has height 0 and no arms. The diameter is the best bend over all nodes.
That gives a single post-order walk. Each call returns the node's height to its parent, and while it has the children's heights in hand, it tracks the two largest arm lengths and updates a running best with their sum. Finding the top two in one pass over the children avoids sorting, which would add a log factor at nodes with many children.
def diameter(root):
best = 0
def height(node):
nonlocal best
first = second = 0
for child in node.children:
arm = height(child) + 1
if arm > first:
first, second = arm, first
elif arm > second:
second = arm
best = max(best, first + second)
return first
if root is not None:
height(root)
return bestThe recursion goes as deep as the tree. Python stops at about a thousand nested calls by default, so on a long chain this version raises RecursionError. The JavaScript version below avoids recursion. It records nodes in an order where every parent comes before its children, then processes that list backward, so each child's height is ready before its parent needs it.
function diameter(root) {
if (root === null) return 0;
const order = [];
const stack = [root];
while (stack.length > 0) {
const node = stack.pop();
order.push(node);
for (const child of node.children) stack.push(child);
}
const height = new Map();
let best = 0;
for (let i = order.length - 1; i >= 0; i--) {
const node = order[i];
let first = 0;
let second = 0;
for (const child of node.children) {
const arm = height.get(child) + 1;
if (arm > first) {
second = first;
first = arm;
} else if (arm > second) {
second = arm;
}
}
height.set(node, first);
if (first + second > best) best = first + second;
}
return best;
}Walk Tree Q by hand. Leaves 60 and 80 have height 0. Node 50 has one arm of length 1, so height 1; 30 has height 2. On the other side 70 has height 1 and 40 has height 2. Node 20 now sees two arms, 3 and 3, so best becomes 6 and its height is 3. The root 10 sees one arm of length 4 and no second arm, so its own bend is only 4, and the answer stays 6.
Another linear method: two searches
If the input is an unrooted tree, there is a classic alternative. Run a search from any node and find a node u that is farthest from it. Then run a second search from u; the largest distance it finds is the diameter. It is O(n) as well and is worth naming when the interviewer hands you an edge list. On a rooted N-ary tree the post-order pass is usually simpler, because it needs no adjacency map and no second traversal.
Complexity
| Approach | Time | Extra space |
|---|---|---|
| BFS from every node | O(n²) | O(n) for the adjacency map and distances |
| Two searches on the undirected tree | O(n) | O(n) |
| Post-order heights, top two arms (recursive) | O(n) | O(h) call stack |
| Post-order heights from an order list (iterative) | O(n) | O(n) for the list and map |
| Sorting each child list to find the top two | O(n log n) worst case | Adds a sort per node for no benefit |
Edge cases
- Empty tree: return 0, and decide this out loud since some versions guarantee at least one node.
- One node: 0, since a path with no edges is still a path.
- A root with a single long chain below it: the answer is the chain length, with one arm only.
- A star with many leaves: 2, the case that catches code using only the first child.
- Tree Q: the longest path avoids the root entirely.
- Two children with equal heights: the second one is not larger than the first, so it must fall through to the second-slot check. Code with only one comparison drops it.
Mistakes that cost points
- Returning the diameter from the recursive function instead of the height. The parent needs a height; the path through a node can never be extended upward.
- Counting nodes instead of edges, which gives an answer one too high. Ask which one the problem wants.
- Adding the heights of the first two children in the list rather than the two tallest.
- Only computing the root's bend, which fails on Tree Q.
- Updating the second-largest value before the largest, so a new maximum overwrites the old one without moving it down.
How to explain it out loud
Fictional example
- Candidate
- Every path has one highest node. From there it drops into at most two children, so the best path bending at a node is its two tallest arms added together.
- Candidate
- I will have each call return the height of its node and, on the way, update a global best with the top two arms. No sorting, just two variables.
- Interviewer
- Does the longest path always pass through the root?
- Candidate
- No. If the root has one child and the real action is lower down, the best bend is lower. That is why I check every node, not just the root.
- Candidate
- It is O(n) time. The recursion is O(h) deep, so for very deep trees I would switch to the iterative order-list version.
Related walkthroughs
N-ary Tree Level Order Traversal works on the same node shape with a breadth-first queue instead. Longest ZigZag Path in a Binary Tree is another "best path anywhere" problem where each node reports small values to its parent, and Most Frequent Subtree Sum uses the same post-order skeleton to return sums. For a distance problem that has to look upward as well as down, see All Nodes Distance K in a Binary Tree.
Practicing with Natively
Natively runs on Mac and Windows and can take a screenshot of a tree problem you are practicing, then answer in its overlay with an approach and code, or with just a hint if that is all you ask for, such as "think about the highest node on the path". It also writes a transcript of a spoken mock round, which makes it easy to check later whether you explained the height-versus-diameter split before coding. The AI interview assistant page describes the setup.
Questions people ask
How do you find the diameter of an N-ary tree?
Do a post-order walk where each node returns its height. At each node, add the two largest values of child height plus one and keep the biggest sum seen anywhere; that is the diameter in edges.
Does the diameter of an N-ary tree pass through the root?
Not necessarily. If the root has one child and the two deepest branches split lower down, the longest path bends at that lower node, so every node has to be checked.
What is the time complexity of Diameter of N-ary Tree?
O(n) time, since each node and each child link is processed once, and O(h) extra space for the recursion, where h is the height.
Is the diameter counted in nodes or edges?
Usually in edges, so a single node has diameter 0 and a root with two leaf children has diameter 2. Confirm it with the interviewer.
Where to go next
Practice with the same assistant you would use on a call: it listens, transcribes and suggests answers from your own resume and the job description.
Facts on this page were last checked on . Product details come from the Natively app itself; if something here is out of date, tell us at hello@heynatively.com.
