Leetcode 652: Find duplicate subtrees

The topic is as follows:
Given a binary tree, return all repeated subtrees. For repeated subtrees of the same type, you only need to return the root node of any one of them.

The duplication of two trees means that they have the same structure and the same node value.

Example 1:

    1
   / \
  2   3
 /   / \
4   2   4
   /
  4

Here are two repeated subtrees:

  2
 /
4

with

4

Source: LeetCode title link: original title

This topic allows us to think about how to use the pre-order, middle-order, and post-order traversal framework of the binary tree. Regarding each traversal, you can see: Recursive and non-recursive implementation of each traversal of the binary tree

Here we want to find the repeated subtrees, so for a subtree, we need to do two things:
1. Know what you look like
2. Know what other subtrees look like

For the first thing, we need to know what the subtree looks like, then we need to do two things:
1. Know what the left subtree looks like
2. Know what the right subtree looks like

When we find both the left and right subtrees, and add our own values, this is what this subtree looks like. Here we serialize the tree to record the appearance of the subtree.

 string str = to_string(root->val) + "," + travel(root->left) + "," + travel(root->right);

This is the core code to find out what the subtree sequence looks like.

Then it is to find whether it is repeated. Here we can use unordered_map to store our sequence, and every time a subtree sequence is found, we judge whether it exists, and if it is, add it to the result.

		if(mp[str]==1) res.push_back(root);//只有一个重复时加入结果
        mp[str]++; //计数+1

So here its recursive traversal form is actually very similar to the pre-order traversal, first access its own value, and then access the left and right subtrees, but it is also very simple to change to similar middle order and post order.

Complete code:

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
    
    
public:
    vector<TreeNode*> res;
    unordered_map<string, int> mp;
    vector<TreeNode*> findDuplicateSubtrees(TreeNode* root) {
    
    
        travel(root);
        return res;
    }
    
    string travel(TreeNode* root){
    
    
        if(root==0) return "";
        //二叉树先序序列化
        string str = to_string(root->val) + "," + travel(root->left) + "," + travel(root->right);
        
        if(mp[str]==1) res.push_back(root);
        mp[str]++;

        return str;
    }
};

Guess you like

Origin blog.csdn.net/weixin_45146520/article/details/109044759