Skip to content

Commit 9de6e09

Browse files
committedFeb 28, 2023
solved: 652. Find Duplicate Subtrees
Signed-off-by: rajput-hemant <rajput.hemant2001@gmail.com>
1 parent 9e27586 commit 9de6e09

File tree

1 file changed

+40
-0
lines changed

1 file changed

+40
-0
lines changed
 
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
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+
}

0 commit comments

Comments
 (0)
Please sign in to comment.