-
Notifications
You must be signed in to change notification settings - Fork 0
/
572.go
137 lines (117 loc) · 2.4 KB
/
572.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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
/*
# ------------------------------ #
# #
# version 0.0.1 #
# #
# Aleksiej Ostrowski, 2023 #
# #
# https://aleksiej.com #
# #
# ------------------------------ #
*/
package main
import (
"fmt"
)
type TreeNode struct {
Val int
Left *TreeNode
Right *TreeNode
}
//https://leetcode.com/problems/subtree-of-another-tree/solutions/3349136/java-easy-solution-0ms-beats100/
func isSubtree(root *TreeNode, subRoot *TreeNode) bool {
if root == nil {
return false
}
if root.Val == subRoot.Val {
if isIdentical(root, subRoot) {
return true
}
}
return isSubtree(root.Left, subRoot) || isSubtree(root.Right, subRoot)
}
func isIdentical(node *TreeNode, subRoot *TreeNode) bool {
if node == nil && subRoot == nil {
return true
} else if node == nil || subRoot == nil || node.Val != subRoot.Val {
return false
}
if !isIdentical(node.Left, subRoot.Left) {
return false
}
if !isIdentical(node.Right, subRoot.Right) {
return false
}
return true
}
/*
// It is not working.
func isSubtree(root *TreeNode, subRoot *TreeNode) bool {
root_v := inorderTraversal(root)
sub_v := inorderTraversal(subRoot)
fmt.Println(root_v)
fmt.Println(sub_v)
for idx_m, el_m := range root_v {
if el_m == sub_v[0] {
sum := 0
idx := idx_m
for _, el_s := range sub_v {
if idx >= len(root_v) {
break
}
if el_s == root_v[idx] {
sum += 1
idx += 1
}
}
if sum == len(sub_v) {
return true
}
}
}
return false
}
func inorderTraversal(root *TreeNode) []int {
var res []int
if root == nil {
return res
}
curr := root
for {
if curr == nil {
break
}
if curr.Left == nil {
res = append(res, curr.Val)
curr = curr.Right
} else {
pre := curr.Left
for {
if pre.Right == nil {
break
}
pre = pre.Right
}
pre.Right = curr
// temp := &TreeNode{curr.Val, curr.Left, curr.Right}
temp := curr
curr = curr.Left
temp.Left = nil
}
}
return res
}
*/
func main() {
/*
tree3 := &TreeNode{3, nil, nil}
tree4 := &TreeNode{4, nil, nil}
tree5 := &TreeNode{5, nil, nil}
tree2 := &TreeNode{2, tree4, tree5}
tree1 := &TreeNode{1, tree2, tree3}
*/
tree1 := &TreeNode{1, nil, nil}
tree2 := &TreeNode{1, nil, nil}
fmt.Println(isSubtree(tree1, tree2))
fmt.Println("ok")
}