本文主要是介绍652. 寻找重复的子树 - 力扣(LeetCode),希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
652. 寻找重复的子树 - 力扣(LeetCode)
/*** 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
参考链接
652. 寻找重复的子树 - 力扣(LeetCode)
寻找重复的子树 - 寻找重复的子树 - 力扣(LeetCode)
[Python/Java/TypeScript/Go] DFS节点编号 - 寻找重复的子树 - 力扣(LeetCode)
这篇关于652. 寻找重复的子树 - 力扣(LeetCode)的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!