File tree 2 files changed +43
-0
lines changed 2 files changed +43
-0
lines changed Original file line number Diff line number Diff line change
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
+ } ;
Original file line number Diff line number Diff line change 490
490
648|[ Replace Words] ( ./0648-replace-words.js ) |Medium|
491
491
649|[ Dota2 Senate] ( ./0649-dota2-senate.js ) |Medium|
492
492
650|[ 2 Keys Keyboard] ( ./0650-2-keys-keyboard.js ) |Medium|
493
+ 652|[ Find Duplicate Subtrees] ( ./0652-find-duplicate-subtrees.js ) |Medium|
493
494
653|[ Two Sum IV - Input is a BST] ( ./0653-two-sum-iv-input-is-a-bst.js ) |Easy|
494
495
654|[ Maximum Binary Tree] ( ./0654-maximum-binary-tree.js ) |Medium|
495
496
680|[ Valid Palindrome II] ( ./0680-valid-palindrome-ii.js ) |Easy|
You can’t perform that action at this time.
0 commit comments