3331. Find Subtree Sizes After Changes
You are given a tree rooted at node 0 that consists of
n
nodes numbered from0
ton - 1
. The tree is represented by an arrayparent
of sizen
, whereparent[i]
is the parent of nodei
. Since node 0 is the root,parent[0] == -1
.You are also given a string
s
of lengthn
, wheres[i]
is the character assigned to nodei
.We make the following changes on the tree one time simultaneously for all nodes
x
from1
ton - 1
:
- Find the closest node
y
to nodex
such thaty
is an ancestor ofx
, ands[x] == s[y]
.- If node
y
does not exist, do nothing.- Otherwise, remove the edge between
x
and its current parent and make nodey
the new parent ofx
by adding an edge between them.Return an array
answer
of sizen
whereanswer[i]
is the size of the subtree rooted at nodei
in the final tree.A subtree of
treeName
is a tree consisting of a node intreeName
and all of its descendants.
1 | class Solution { |