Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
Skip to content

Commit ecb7e5d

Browse files
committed
Add solution #652
1 parent 5b31661 commit ecb7e5d

File tree

2 files changed

+43
-0
lines changed

2 files changed

+43
-0
lines changed

0652-find-duplicate-subtrees.js

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
/**
2+
* 652. Find Duplicate Subtrees
3+
* https://leetcode.com/problems/find-duplicate-subtrees/
4+
* Difficulty: Medium
5+
*
6+
* Given the root of a binary tree, return all duplicate subtrees.
7+
*
8+
* For each kind of duplicate subtrees, you only need to return the root node of any one of them.
9+
*
10+
* Two trees are duplicate if they have the same structure with the same node values.
11+
*/
12+
13+
/**
14+
* Definition for a binary tree node.
15+
* function TreeNode(val, left, right) {
16+
* this.val = (val===undefined ? 0 : val)
17+
* this.left = (left===undefined ? null : left)
18+
* this.right = (right===undefined ? null : right)
19+
* }
20+
*/
21+
/**
22+
* @param {TreeNode} root
23+
* @return {TreeNode[]}
24+
*/
25+
var findDuplicateSubtrees = function(root) {
26+
const map = new Map();
27+
const result = [];
28+
29+
serialize(root);
30+
31+
return result;
32+
33+
function serialize(node) {
34+
if (!node) return '#';
35+
const key = `${node.val},${serialize(node.left)},${serialize(node.right)}`;
36+
map.set(key, (map.get(key) || 0) + 1);
37+
if (map.get(key) === 2) {
38+
result.push(node);
39+
}
40+
return key;
41+
}
42+
};

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -490,6 +490,7 @@
490490
648|[Replace Words](./0648-replace-words.js)|Medium|
491491
649|[Dota2 Senate](./0649-dota2-senate.js)|Medium|
492492
650|[2 Keys Keyboard](./0650-2-keys-keyboard.js)|Medium|
493+
652|[Find Duplicate Subtrees](./0652-find-duplicate-subtrees.js)|Medium|
493494
653|[Two Sum IV - Input is a BST](./0653-two-sum-iv-input-is-a-bst.js)|Easy|
494495
654|[Maximum Binary Tree](./0654-maximum-binary-tree.js)|Medium|
495496
680|[Valid Palindrome II](./0680-valid-palindrome-ii.js)|Easy|

0 commit comments

Comments
 (0)