3327. Check if DFS Strings Are Palindromes
You are given a tree rooted at node 0, consisting 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
.Consider an empty string
dfsStr
, and define a recursive functiondfs(int x)
that takes a nodex
as a parameter and performs the following steps in order:
- Iterate over each child
y
ofx
in increasing order of their numbers, and calldfs(y)
.- Add the character
s[x]
to the end of the stringdfsStr
.Note that
dfsStr
is shared across all recursive calls ofdfs
.You need to find a boolean array
answer
of sizen
, where for each indexi
from0
ton - 1
, you do the following:
- Empty the string
dfsStr
and calldfs(i)
.- If the resulting string
dfsStr
is a palindrome, then setanswer[i]
totrue
. Otherwise, setanswer[i]
tofalse
.Return the array
answer
.A palindrome is a string that reads the same forward and backward.
1 | class Solution { |