-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathproblem048.go
More file actions
70 lines (62 loc) · 1.58 KB
/
Copy pathproblem048.go
File metadata and controls
70 lines (62 loc) · 1.58 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
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
package problem048
type TreeNode struct {
value rune
leftChild *TreeNode
rightChild *TreeNode
}
func (thisNode *TreeNode) Equal(other *TreeNode) bool {
if thisNode == nil || other == nil {
return thisNode == nil && other == nil
}
childEqualityChannel := make(chan bool, 2)
go func() {
childEqualityChannel <- thisNode.leftChild.Equal(other.leftChild)
}()
childEqualityChannel <- thisNode.rightChild.Equal(other.rightChild)
signalCount := 0
for signalCount < 2 {
select {
case childEquality := <-childEqualityChannel:
signalCount++
if !childEquality {
return false
}
}
}
return thisNode.value == other.value
}
type Order int
const (
PREORDER = Order(0)
INORDER = Order(1)
POSTORDER = Order(2)
)
func FromValues(values []rune, order Order) *TreeNode {
if len(values) == 0 {
return nil
}
var leftChildValues, rightChildValues []rune
var rootValue rune
// presume the tree is balanced
switch order {
case PREORDER:
rootValue = values[0]
childValues := values[1:]
mid := len(childValues) / 2
leftChildValues, rightChildValues = childValues[:mid], childValues[mid:]
case INORDER:
mid := len(values) / 2
rootValue = values[mid]
leftChildValues, rightChildValues = values[:mid], values[mid+1:]
case POSTORDER:
rootValue = values[len(values)-1]
childValues := values[:len(values)-1]
mid := len(childValues) / 2
leftChildValues, rightChildValues = childValues[:mid], childValues[mid:]
}
return &TreeNode{
value: rootValue,
leftChild: FromValues(leftChildValues, order),
rightChild: FromValues(rightChildValues, order),
}
}