Clarify and Prune an N-ary Tree to a Depth Limit
SnowflakeSoftware Engineer · Technical ScreenLast updated
This problem tests tree traversal techniques and recursive state management by requiring the pruning of an N-ary tree nodes based on a depth constraint while maintaining valid structural connectivity.
Problem Statement
You are given the root of an N-ary tree where each node contains an integer value and a list of children. Given an integer max_depth, prune the tree such that no node exists at a depth strictly greater than max_depth. The root of the tree is at depth 0.
Your task is to return the pruned tree. If the root itself exceeds the depth limit (e.g., if max_depth is negative), return None.
Function Signature
class Node:
def __init__(self, val=None, children=None):
self.val = val
self.children = children if children is not None else []
def prune_tree(root: 'Node', max_depth: int) -> 'Node':
Constraints
max_depth>= -1- The tree can have up to 10^5 nodes.
- A node's
childrenlist may be empty (leaf node).
Examples
Example 1:
Input: root = [1, [2, [4]], [3]], max_depth = 1
Output: [1, [2], [3]]
Explanation: Node 4 is at depth 2, which is > 1, so it is removed.
Example 2:
Input: root = [1, [2]], max_depth = 0
Output: [1]
Explanation: Only the root remains; children are removed.
Edge Cases
- Empty root (
None). max_depth = 0(only the root should remain).max_depth = -1(the entire tree is pruned).
Hints
Hint 1
Consider a recursive approach where the function receives the current node and its current depth as arguments.
Hint 2
If the current node's depth equals the `max_depth`, prune its entire list of children by setting the list to empty.
Hint 3
If the current node's depth is less than the `max_depth`, recursively call the pruning function on each child.
Follow-up questions
- How would you modify your solution if you were required to return the total number of nodes deleted during the pruning process?
- What is the time and space complexity of your solution in terms of total nodes N and the depth of the tree?
- How would your approach change if nodes contained references to their parents, and you needed to maintain the integrity of those pointers?
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.