File tree 1 file changed +40
-0
lines changed
src/0601-0700/652 - Find Duplicate Subtrees
1 file changed +40
-0
lines changed Original file line number Diff line number Diff line change
1
+ package main
2
+
3
+ import "strconv"
4
+
5
+ // Definition for a binary tree node.
6
+ type TreeNode struct {
7
+ Val int
8
+ Left * TreeNode
9
+ Right * TreeNode
10
+ }
11
+
12
+ func findDuplicateSubtrees (root * TreeNode ) []* TreeNode {
13
+ // to store the hash value of subtrees
14
+ hashMap := make (map [string ]int )
15
+ // to store the result
16
+ res := make ([]* TreeNode , 0 )
17
+ // traverse the tree
18
+ traverse (root , hashMap , & res )
19
+ return res
20
+ }
21
+
22
+ // traverse the tree
23
+ func traverse (root * TreeNode , hashMap map [string ]int , res * []* TreeNode ) string {
24
+ // if the root is nil, return "#"
25
+ if root == nil {
26
+ return "#"
27
+ }
28
+ // traverse the left and right subtree
29
+ left := traverse (root .Left , hashMap , res )
30
+ right := traverse (root .Right , hashMap , res )
31
+ // get the hash value of the subtree
32
+ subTree := left + "," + right + "," + strconv .Itoa (root .Val )
33
+ // if the hash value of the subtree is 1, it means that the subtree is duplicated
34
+ if hashMap [subTree ] == 1 {
35
+ * res = append (* res , root )
36
+ }
37
+ // add the hash value of the subtree to the hashMap
38
+ hashMap [subTree ]++
39
+ return subTree
40
+ }
You can’t perform that action at this time.
0 commit comments