⚡Flashcard Drill➔
NeetCode #410LC-1506MediumTreesNC Algo100
← Back to All Problems

#410 · #1506 · Find Root of N-Ary Tree(找到 N 叉树的根节点)

📌 Problem Statement & Constraints

You are given all the nodes of an N-ary tree as an array. Each node has a unique value and a children list. Return the root of the tree. Constraints: the number of nodes is in [1, 5 * 10^4], 1 <= Node.val <= 5 * 10^4.

💡 Core Algorithmic Approaches

  1. The root is the only node that never appears as anyone's child.
  2. Collect every node that appears in some children list, then find the node absent from that set.
  3. Node objects are hashable by identity in Python, so a set of objects works directly.
  4. This is O(n) and needs no traversal of the tree structure.

💻 Benchmark Python3 Implementation

class Solution:
    def findRoot(self, tree: "List[Node]") -> "Node":
        children = set()
        for node in tree:
            for c in node.children:
                children.add(c)            # identity-based membership
        for node in tree:
            if node not in children:       # never a child -> the root
                return node
        return None

⚡ Complexity Deep Dive

⏱️ Time Complexity
O(n): one pass over the nodes and their children.
💾 Space Complexity
O(n) for the set of children.

⚠️ Interview Pitfalls & Follow-ups

  • Using values instead of node objects: values are unique here so it would work, but identity is the direct statement of the property.
  • Traversing the tree to find the root: you do not have a starting point, which is the whole difficulty of the problem.
  • Forgetting that a node may appear as a child only once: the set handles it either way.
  • Assuming the array is ordered: it is not; the root may be anywhere.
⚡
Test muscle memory on this topic via 3-Layer Flashcards
Active Recall: Mentally formulate Prompt ➔ Math Derivation ➔ Benchmark Implementation in 3 minutes.
🎯 Drill This Card Now➔

🧩 Related Trees Problems

中文速览与面试要点

找到 N 叉树的根节点

(这是一个 交互式问题 )给你一个 N 叉树的所有节点(它们以任意顺序存储),请你找出并返回这棵树的 根节点 。N 叉树的所有节点由若干节点组成,其中每个节点最多有一个父节点。树的 根节点 是树中唯一没有父节点的节点。约束:1 ≤ tree.length ≤ 5 × 10^4;0 ≤ Node.val &lt; tree.length;树中每个节点都有唯一的 val。

核心要点

  • 求和作差(O(n) 时间、O(1) 空间,推荐) :所有节点值之和减去所有子节点值之和,差值恰好是根节点的值。
  • 为什么成立 :除根节点外,每个节点都恰好作为某个节点的子节点出现一次,因此在「子节点值之和」中被计入一次;只有根节点从未作为子节点出现。
  • 然后线性查找该值对应的节点 :第二次遍历即可找到根节点。
  • 哈希集合方案 :把所有子节点值放入集合,再找不在集合中的节点——也是 O(n),但空间 O(n)。

常见陷阱

  • 用哈希集合记录子节点再查找 :正确但空间 O(n);求和法只需 O(1)。
  • 忘记遍历所有子节点 : child_sum 必须包含每个节点的所有子节点值。
  • 误以为「出现次数最少」的节点就是根 :本题用「从未作为子节点出现」判定更准确。

参考实现

class Solution:
    def findRoot(self, tree: list) -> 'Node':
        total = 0
        child_sum = 0
        for node in tree:
            total += node.val
            for c in node.children:
                child_sum += c.val
        root_val = total - child_sum        # 差值即根节点值

        for node in tree:
            if node.val == root_val:
                return node
        return None