Problem solution · C++

Count Paths That Can Form a Palindrome in a Tree

Count Paths That Can Form a Palindrome in a Tree: a C++ solution using depth-first search. Learn the idea, check the complexity, and read the full code, with credit to walkccc LeetCode Solutions.

Technique
Depth-first search
Source
walkccc LeetCode Solutions
Length
39 lines
Start with the idea.

Try the problem first. If you get stuck, read the approach below, then write your own solution. The full code is at the bottom.

Approach

Depth-first search

For Count Paths That Can Form a Palindrome in a Tree, the implementation follows one branch at a time, making it suitable for components, trees, backtracking, or dependency exploration.

  1. Define the state carried into one recursive or stack frame.
  2. Mark or choose the current state before exploring children.
  3. Combine child results or undo the choice when the branch finishes.

Code notes

  • 39 lines of C++ from the credited upstream file 2791.cpp.
  • The implementation visibly relies on sequence storage, hash lookup.
  • 3 loop blocks detected, together with recursive traversal.

Complexity

Count unique states for graph traversal; for backtracking, count the branching factor and maximum depth.

Check the problem constraints before deciding whether this complexity will pass.

Source

Code and credit

This code comes from walkccc LeetCode Solutions by P.-Y. Chen (walkccc) and is used under the MIT licence.

Full codeCount Paths That Can Form a Palindrome in a Tree · C++C++
Use this to learn the idea, then write your own version.
class Solution { public:  long long countPalindromePaths(vector<int>& parent, string s) {    // A valid (u, v) has at most 1 letter with odd frequency on its path. The    // frequency of a letter on the u-v path is equal to the sum of its    // frequencies on the root-u and root-v paths substract twice of its    // frequency on the root-LCA(u, v) path. Considering only the parity    // (even/odd), the part involving root-LCA(u, v) can be ignored, making it    // possible to calculate both parts easily using a simple DFS.    vector<vector<int>> tree(parent.size());     for (int i = 1; i < parent.size(); ++i)      tree[parent[i]].push_back(i);     return dfs(tree, 0, 0, s, {{0, 1}});  }  private:  // mask := 26 bits that represent the parity of each character in the alphabet  // on the path from node 0 to node u  long dfs(const vector<vector<int>>& tree, int u, int mask, const string& s,           unordered_map<int, int>&& maskToCount) {    long res = 0;    if (u > 0) {      mask ^= 1 << (s[u] - 'a');      // Consider any u-v path with 1 bit set.      for (int i = 0; i < 26; ++i)        if (const auto it = maskToCount.find(mask ^ (1 << i));            it != maskToCount.cend())          res += it->second;      // Consider u-v path with 0 bit set.      res += maskToCount[mask ^ 0]++;    }    for (const int v : tree[u])      res += dfs(tree, v, mask, s, std::move(maskToCount));    return res;  }}; 

Did this explanation save you time? I'm a Grade 11 student building this free library to make difficult algorithms easier to understand.

Buy me a coffee ↗