/**
* Definition for a binary tree node.
* function TreeNode(val, left, right) {
* this.val = (val===undefined ? 0 : val)
* this.left = (left===undefined ? null : left)
* this.right = (right===undefined ? null : right)
* }
*/
/**
* @param {TreeNode} root
* @return {TreeNode[]}
*/
var findDuplicateSubtrees = function(root) {
const seen = new Map();
const repeat = new Set();
const dfs = (node) => {
if (!node) {
return "";
}
let sb = '';
sb += node.val;
sb += "(";
sb += dfs(node.left);
sb += ")(";
sb += dfs(node.right);
sb += ")";
if (seen.has(sb)) {
repeat.add(seen.get(sb));
} else {
seen.set(sb, node);
}
return sb;
}
dfs(root);
return [...repeat];
};
执行结果:通过
执行用时:108 ms, 在所有 JavaScript 提交中击败了67.16%的用户
内存消耗:48.7 MB, 在所有 JavaScript 提交中击败了43.14%的用户
通过测试用例:176 / 176
var findDuplicateSubtrees = function(root) {
const seen = new Map();
const repeat = new Set();
let idx = 0;
const dfs = (node) => {
if (!node) {
return 0;
}
const tri = [node.val, dfs(node.left), dfs(node.right)];
const hash = tri.toString();
if (seen.has(hash)) {
const pair = seen.get(hash);
repeat.add(pair[0]);
return pair[1];
} else {
seen.set(hash, [node, ++idx]);
return idx;
}
}
dfs(root);
return [...repeat];
};
执行结果:通过
执行用时:80 ms, 在所有 JavaScript 提交中击败了98.28%的用户
内存消耗:48.3 MB, 在所有 JavaScript 提交中击败了70.10%的用户
通过测试用例:176 / 176
寻找重复的子树 - 寻找重复的子树 - 力扣(LeetCode)
[Python/Java/TypeScript/Go] DFS节点编号 - 寻找重复的子树 - 力扣(LeetCode)