-
Notifications
You must be signed in to change notification settings - Fork 0
/
question43.go
60 lines (48 loc) · 912 Bytes
/
question43.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
package chapter07
import "github.com/syhily/code-interviews/common"
type TreeNode struct {
value int
left *TreeNode
right *TreeNode
}
type CBTInserter interface {
insert(value int) *TreeNode
root() *TreeNode
}
type cbtInserter struct {
tree *TreeNode
queue common.Queue[*TreeNode]
}
func (c *cbtInserter) insert(value int) *TreeNode {
parent := c.queue.Element()
node := &TreeNode{value: value}
if parent.left == nil {
parent.left = node
c.queue.Add(node)
} else {
parent.right = node
c.queue.Add(node)
c.queue.Remove()
}
return parent
}
func (c *cbtInserter) root() *TreeNode {
return c.tree
}
func newCBTInserter(node *TreeNode) CBTInserter {
q := common.NewQueue[*TreeNode]()
q.Add(node)
for {
n := q.Element()
if n.left == nil || n.right == nil {
break
}
q.Add(n.left)
q.Add(n.right)
q.Remove()
}
return &cbtInserter{
tree: node,
queue: q,
}
}