-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdup_trees.go
51 lines (43 loc) · 1.11 KB
/
dup_trees.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
package problem0652
import (
. "leetcodedaily/helpers/binarytree"
"strconv"
"strings"
)
/*
Given the root of a binary tree, return all duplicate subtrees.
For each kind of duplicate subtrees, you only need to return the root node of any one of them.
Two trees are duplicate if they have the same structure with the same node values.
*/
// The idea here is to seralize the subtrees as we go and check for duplicates
func findDuplicateSubtrees(root *TreeNode) []*TreeNode {
var res []*TreeNode
var seen = map[string]bool{}
var dfs func(head *TreeNode) string
dfs = func(head *TreeNode) string {
var str strings.Builder
var rstr string
if head == nil {
return ",NIL"
}
// Serialize the tree
str.WriteByte(',')
str.WriteString(strconv.Itoa(head.Val))
str.WriteString(dfs(head.Left))
str.WriteString(dfs(head.Right))
rstr = str.String()
// If we've seen the subtree before
if done, ok := seen[rstr]; ok {
// Make sure to only include one of each tree
if !done {
res = append(res, head)
seen[rstr] = true
}
} else {
seen[rstr] = false
}
return rstr
}
dfs(root)
return res
}