File tree Expand file tree Collapse file tree 1 file changed +52
-0
lines changed Expand file tree Collapse file tree 1 file changed +52
-0
lines changed Original file line number Diff line number Diff line change 1+ /**
2+ * Definition for a binary tree node.
3+ * function TreeNode(val, left, right) {
4+ * this.val = (val===undefined ? 0 : val)
5+ * this.left = (left===undefined ? null : left)
6+ * this.right = (right===undefined ? null : right)
7+ * }
8+ */
9+ /**
10+ * Hashing
11+ * Time O(n^2) | Space O(n^2)
12+ * https://leetcode.com/problems/find-duplicate-subtrees/
13+ * @param {TreeNode } root
14+ * @return {TreeNode[] }
15+ */
16+ var findDuplicateSubtrees = function ( root ) {
17+
18+ const stringHash = { } ;
19+
20+ const makePreOrderStr = ( node , str ) => {
21+ if ( ! node ) return str + "-" + "null" ;
22+
23+ const str1 = makePreOrderStr ( node . left , str + "-" + node . val ) ;
24+ const str2 = makePreOrderStr ( node . right , str1 ) ;
25+
26+ return str2 ;
27+ }
28+
29+ const duplicates = [ ] ;
30+
31+ const dfs = ( node ) => {
32+ if ( ! node ) return ;
33+ const str = makePreOrderStr ( node , "" ) ;
34+
35+ if ( ! stringHash [ str ] ) {
36+ stringHash [ str ] = [ ] ;
37+ }
38+
39+ stringHash [ str ] . push ( node ) ;
40+
41+ dfs ( node . left ) ;
42+ dfs ( node . right ) ;
43+ }
44+
45+ dfs ( root ) ;
46+
47+ for ( let key in stringHash ) {
48+ if ( stringHash [ key ] . length > 1 ) duplicates . push ( stringHash [ key ] [ 0 ] ) ;
49+ }
50+
51+ return duplicates ;
52+ } ;
You can’t perform that action at this time.
0 commit comments