2023-02-28 Daily Challenge

Today I have done leetcode's February LeetCoding Challenge with cpp.

February LeetCoding Challenge 28

Description

Find Duplicate Subtrees

Given the root of a binary tree, return all duplicate subtrees.

For each kind of duplicate subtrees, you only need to return the root node of any one of them.

Two trees are duplicate if they have the same structure with the same node values.

 

Example 1:

Input: root = [1,2,3,4,null,2,4,null,null,4]
Output: [[2,4],[4]]

Example 2:

Input: root = [2,1,1]
Output: [[1]]

Example 3:

Input: root = [2,2,2,3,null,3,null]
Output: [[2,3],[3]]

 

Constraints:

  • The number of the nodes in the tree will be in the range [1, 5000]
  • -200 <= Node.val <= 200

Solution

class Solution {
  unordered_map<string, vector<TreeNode*>> sameExpr;
  string visit(TreeNode *root) {
    if(!root) return "#";
    
    string result = to_string(root->val) + "," + visit(root->left) + "," + visit(root->right);
    sameExpr[result].push_back(root);
    return result;
  }
public:
  vector<TreeNode*> findDuplicateSubtrees(TreeNode* root) {
    string tmp;
    visit(root);

    vector<TreeNode*> answer;
    for(const auto &[ _expr, roots] : sameExpr) {
      if(roots.size() > 1) answer.push_back(roots.front());
    }
    return answer;
  }
};

// Accepted
// 175/175 cases passed (27 ms)
// Your runtime beats 79.61 % of cpp submissions
// Your memory usage beats 38.15 % of cpp submissions (43.7 MB)