Maximize non-adjacent sum on an N-ary tree
ZipHQSoftware Engineer · Technical ScreenLast updated
This question evaluates skills in tree-based dynamic programming, recursive traversal, and per-node state management for selecting non-adjacent nodes in an N-ary tree.
You are given an N-ary tree (each node may have 0..k children). Each node contains an integer value (can be 0 or positive).
You want to select a set of nodes such that no selected node is directly connected to another selected node (i.e., you cannot select both a node and any of its children). Return the maximum possible sum of selected node values.
Requirements
- Implement a tree node structure yourself, e.g.:
value: intchildren: List[Node]- Write a function
maxNonAdjacentTreeSum(root) -> int.
Input / Output
- Input:
rootpointer/reference to the root node (ornullfor empty tree). - Output: an integer representing the maximum achievable sum.
Example
If the tree is:
- Root 3 with children 2 and 3
- Node 2 has child 3
- Node 3 (child of root) has child 1
One optimal selection is nodes with values 3 (root) + 3 (grandchild under 2) + 1 = 7, so return 7.
Constraints
- Number of nodes
nup to ~10^5. - Aim for O(n) time.
- Extra space should be proportional to recursion depth or explicit stack size.
Solution walkthrough is for members
Get the full walkthrough with reference code and complexity analysis, plus Kitty Coach at 300 messages a day. Hints, the code runner and community answers stay free.