forked from neetcode-gh/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
0652-find-duplicate-subtrees.js
52 lines (40 loc) · 1.18 KB
/
0652-find-duplicate-subtrees.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
/**
* 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)
* }
*/
/**
* Hashing
* Time O(n^2) | Space O(n^2)
* https://leetcode.com/problems/find-duplicate-subtrees/
* @param {TreeNode} root
* @return {TreeNode[]}
*/
var findDuplicateSubtrees = function(root) {
const stringHash = {};
const makePreOrderStr = (node, str) => {
if(!node) return str + "-" + "null";
const str1 = makePreOrderStr(node.left, str + "-" + node.val);
const str2 = makePreOrderStr(node.right, str1);
return str2;
}
const duplicates = [];
const dfs = (node) => {
if(!node) return;
const str = makePreOrderStr(node, "");
if(!stringHash[str]) {
stringHash[str] = [];
}
stringHash[str].push(node);
dfs(node.left);
dfs(node.right);
}
dfs(root);
for (let key in stringHash) {
if(stringHash[key].length > 1) duplicates.push(stringHash[key][0]);
}
return duplicates;
};