Class Solution
-
- All Implemented Interfaces:
public final class Solution3331 - Find Subtree Sizes After Changes.
Medium
You are given a tree rooted at node 0 that consists of
nnodes numbered from0ton - 1. The tree is represented by an arrayparentof sizen, whereparent[i]is the parent of nodei. Since node 0 is the root,parent[0] == -1.You are also given a string
sof lengthn, wheres[i]is the character assigned to nodei.We make the following changes on the tree one time simultaneously for all nodes
xfrom1ton - 1:Find the closest node
yto nodexsuch thatyis an ancestor ofx, ands[x] == s[y].If node
ydoes not exist, do nothing.Otherwise, remove the edge between
xand its current parent and make nodeythe new parent ofxby adding an edge between them.
Return an array
answerof sizenwhereanswer[i]is the size of the subtree rooted at nodeiin the final tree.A subtree of
treeNameis a tree consisting of a node intreeNameand all of its descendants.Example 1:
Input: parent = -1,0,0,1,1,1, s = "abaabc"
Output: 6,3,1,1,1,1
Explanation:
The parent of node 3 will change from node 1 to node 0.
Example 2:
Input: parent = -1,0,4,0,1, s = "abbba"
Output: 5,2,1,1,1
Explanation:
The following changes will happen at the same time:
The parent of node 4 will change from node 1 to node 0.
The parent of node 2 will change from node 4 to node 1.
Constraints:
n == parent.length == s.length<code>1 <= n <= 10<sup>5</sup></code>
0 <= parent[i] <= n - 1for alli >= 1.parent[0] == -1parentrepresents a valid tree.sconsists only of lowercase English letters.
-
-
Constructor Summary
Constructors Constructor Description Solution()
-
Method Summary
Modifier and Type Method Description final IntArrayfindSubtreeSizes(IntArray parent, String s)-
-
Method Detail
-
findSubtreeSizes
final IntArray findSubtreeSizes(IntArray parent, String s)
-
-
-
-