Skip to content

Commit f6a8d89

Browse files
authored
Create 652-find-duplicate-subtrees.js
1 parent 8023f07 commit f6a8d89

File tree

1 file changed

+27
-0
lines changed

1 file changed

+27
-0
lines changed

652-find-duplicate-subtrees.js

+27
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
/**
2+
* Definition for a binary tree node.
3+
* function TreeNode(val) {
4+
* this.val = val;
5+
* this.left = this.right = null;
6+
* }
7+
*/
8+
/**
9+
* @param {TreeNode} root
10+
* @return {TreeNode[]}
11+
*/
12+
const findDuplicateSubtrees = function (root) {
13+
const obj = {},
14+
res = []
15+
preOrder(root, obj, res)
16+
return res
17+
}
18+
19+
function preOrder(root, map, res) {
20+
if (root === null) return '#'
21+
const str =
22+
root.val + preOrder(root.left, map, res) + preOrder(root.right, map, res)
23+
if (!map[str]) map[str] = 0
24+
map[str]++
25+
if (map[str] === 2) res.push(root)
26+
return str
27+
}

0 commit comments

Comments
 (0)