A topic

The second code

let findDuplicateSubtrees = function(root){
    // Use map to store all subtree sequences and count them
    let map={};
    // Store the duplicate subtree
    let res=[];
    // Define the helper function to recursively solve the problem, sequence the subtree into a string, determine whether the string exists in the map
    let helper=function(root){
        // Empty nodes are represented by #
        if(! root)return "#";
        // Call recursively to get all strings
        let subString=helper(root.left)+', '+helper(root.right)+', '+root.val.toString();
        if(map[subString]===1) {// If the string is present in map, put the subtree in res
            res.push(root);
            map[subString]+=1;
        }else if(! map[subString]){ map[subString]=1;
        }
        return subString;
    }
    helper(root);
    return res;
}
Copy the code