Problem
There is a family tree rooted at 0 consisting of n nodes numbered 0
to n - 1. You are given a 0-indexed integer array parents, where
parents[i] is the parent for node i. Since node 0 is the root ,
parents[0] == -1.
There are 105 genetic values, each represented by an integer in the
inclusive range [1, 105]. You are given a 0-indexed integer array
nums, where nums[i] is a distinct genetic value for node i.
Return an arrayans of lengthn whereans[i]is thesmallest genetic value that is missing from the subtree rooted at node i.
The subtree rooted at a node x contains node x and all of its
descendant nodes.
Examples
Example 1
| |
Example 2
| |
Example 3
| |
Constraints
n == parents.length == nums.length2 <= n <= 10^50 <= parents[i] <= n - 1fori != 0parents[0] == -1parentsrepresents a valid tree.1 <= nums[i] <= 10^5- Each
nums[i]is distinct.
Solution
Method 1 – DFS from 1’s Path (Efficient Subtree Marking)
Intuition
If 1 is not present in the tree, all answers are 1. Otherwise, only nodes on the path from the node with value 1 to the root can have answers greater than 1. We can use DFS to mark all genetic values in the subtree and incrementally find the smallest missing value.
Approach
- Build the tree as an adjacency list.
- Find the node with value 1. If not present, all answers are 1.
- For each node on the path from the node with value 1 to the root, do DFS to mark all genetic values in its subtree.
- For each such node, incrementally find the smallest missing value.
- For all other nodes, answer is 1.
Code
| |
| |
| |
Complexity
- ⏰ Time complexity:
O(n)— Each node is visited at most twice. - 🧺 Space complexity:
O(n)— For the tree and seen set/array.