← Questions

Maximum path sum in an N-ary tree

0
NuroCodingLast asked Jan 2026

A coding interview question asked in Nuro's technical phone screen, last asked Jan 2026. It tests trees, dfs and recursion.

Each node of an N-ary tree holds an integer, which may be negative, and has any number of children. A path is a sequence of nodes joined by parent–child edges that visits each node at most once; it may start and end at any nodes. Return the largest sum of node values along any path.

Interface

Unless you agree on a different interface with the interviewer, assume:

  • class Node: val: int; children: list[Node]
  • max_path_sum(root: Node) -> int. The tree has at least one node, and a path has at least one node.

Example

        1
      / | \
     2  3  4
       / \
      5  -6

max_path_sum(root)  ->  13      # 5 -> 3 -> 1 -> 4

max_path_sum(Node(-5))  ->  -5  # a single negative node is still a path

Constraints

  • Up to 10^5 nodes; the tree may be a long chain.
  • Values are integers in [-10^4, 10^4].

Clarifying questions

  • Must a path contain at least one node? (Then an all-negative tree returns its largest value.)
  • Can a path go down from a node into two different children?
  • Do we need the path, or only the sum?

What a strong answer covers

  • Post-order DFS returning each node's best downward gain: val + max(0, best child gain).
  • The best path through a node uses its two largest non-negative child gains: val + top1 + top2; finding the top two in one pass over the children instead of sorting.
  • Tracking the global maximum, initialized to negative infinity (not 0) so all-negative trees work.
  • O(n) time and O(h) stack; an iterative version for deep chains.
  • Tests with the example, a single node, all negative values and a chain.

Follow-ups

  • Return the nodes on the best path.
  • Restrict paths to go only downward from some node to a descendant.
  • The tree is given as an edge list with no root. What changes?

Where it's asked

  • Nuro · Technical phone screen · Last asked Jan 2026

What it tests

trees · dfs · recursion

Write and test your solution herePython in your browser, the question's tests level by level, every submission kept for you.Sign in to start coding