-
Notifications
You must be signed in to change notification settings - Fork 0
/
question56.go
64 lines (51 loc) · 1.15 KB
/
question56.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
package chapter08
import "github.com/syhily/code-interviews/common"
// Two sum implementation in BST
func twoSum(node *common.TreeNode[int], num int) bool {
next := leftPointer(node)
prev := rightPointer(node)
if next.hasNext() && prev.hasPrev() {
l, r := next.next(), prev.prev()
for l < r {
v := l + r
if v < num {
l = next.next()
} else if v > num {
r = prev.prev()
} else {
return true
}
}
}
return false
}
func leftPointer(node *common.TreeNode[int]) BSTIterator {
return newBSTIterator(node)
}
func rightPointer(node *common.TreeNode[int]) ReservedBSTIterator {
return &reservedBSTIterator{
head: node,
stack: common.NewStack[*common.TreeNode[int]](),
}
}
type ReservedBSTIterator interface {
hasPrev() bool
prev() int
}
type reservedBSTIterator struct {
head *common.TreeNode[int]
stack common.Stack[*common.TreeNode[int]]
}
func (r *reservedBSTIterator) prev() int {
for r.head != nil {
r.stack.Push(r.head)
r.head = r.head.Right
}
r.head = r.stack.Pop()
val := r.head.Value
r.head = r.head.Left
return val
}
func (r *reservedBSTIterator) hasPrev() bool {
return !r.stack.Empty() || r.head != nil
}