-
Notifications
You must be signed in to change notification settings - Fork 0
/
bst_tree_inorder_succ.go
75 lines (62 loc) · 1.22 KB
/
bst_tree_inorder_succ.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
// 285. Inorder Successor in BST
// medium
// Given a binary search tree and a node in it, find the in-order successor of that node in the BST.
package main
import (
"fmt"
"log"
)
type TreeNode struct {
Val int
Left *TreeNode
Right *TreeNode
}
func main() {
tree := buildTree([]int{2,1,3}, 0)
print(tree)
fmt.Println(inorderSuccessor(tree, tree.Left).Val)
}
var found bool
func inorderSuccessor(root *TreeNode, p *TreeNode) *TreeNode {
found = false
return traverse(root, p)
}
func traverse(root, p *TreeNode) *TreeNode {
var res *TreeNode
if root == nil {
return nil
}
//left
res = traverse(root.Left, p)
if res != nil {
return res
}
// visit
if root.Val == p.Val {
found = true
} else if found {
return root
}
//right
return traverse(root.Right, p)
}
func buildTree(tree []int, idx int) *TreeNode {
if idx>=len(tree) || tree[idx]<0 {
return nil
}
node := TreeNode{
Val: tree[idx],
Left: buildTree(tree, (idx+1)*2-1),
Right: buildTree(tree, (idx+1)*2),
}
return &node
}
func print(root *TreeNode) {
if root != nil {
log.Println("Node:", root.Val)
print(root.Left)
print(root.Right)
} else {
log.Println(root)
}
}