-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy paths0652_find_duplicate_subtrees.go
More file actions
43 lines (38 loc) · 1.1 KB
/
s0652_find_duplicate_subtrees.go
File metadata and controls
43 lines (38 loc) · 1.1 KB
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
/*
https://leetcode.com/problems/find-duplicate-subtrees/
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.
*/
package solutions
func findDuplicateSubtrees(root *TreeNode) []*TreeNode {
h := make(map[string]bool)
var duplicates []*TreeNode
var findDuplicateChild func(root *TreeNode) []byte
findDuplicateChild = func(root *TreeNode) []byte {
if root == nil {
return []byte{0, 0}
}
val := root.Val + 201
result := []byte{byte(val >> 8), byte(val)}
for _, child := range [...]*TreeNode{root.Left, root.Right} {
childResult := findDuplicateChild(child)
if child != nil {
if added, exist := h[string(childResult)]; exist {
if !added {
duplicates = append(duplicates, child)
h[string(childResult)] = true
}
} else {
h[string(childResult)] = false
}
}
result = append(result, childResult...)
}
return result
}
findDuplicateChild(root)
return duplicates
}