#3327

Check if DFS Strings Are Palindromes

grandmaster · 2210 · lc hard +32 · 20.1% accepted · 78 likes · top 1%

Description

You are given a tree rooted at node 0 with n nodes numbered 0 to n - 1. The tree is described by an array parent of size n, where parent[i] is the parent of node i; since node 0 is the root, parent[0] == -1.

You are also given a string s of length n, where s[i] is the character assigned to node i.

Define an empty string dfsStr and a recursive function dfs(int x) that:

- Visits each child y of x in increasing order and calls dfs(y).

- Appends the character s[x] to dfsStr.

Note that dfsStr is shared across all recursive calls.

Build a boolean array answer of size n. For each index i from 0 to n - 1:

- Reset dfsStr to empty and call dfs(i).

- Set answer[i] to true if the resulting dfsStr is a palindrome, otherwise false.

Return the array answer.

Code

1
2
3