-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLCCI0406-Successor.go
More file actions
112 lines (102 loc) · 2.54 KB
/
LCCI0406-Successor.go
File metadata and controls
112 lines (102 loc) · 2.54 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
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
package main
// 面试题 04.06. Successor LCCI
// Write an algorithm to find the "next" node (i.e., in-order successor) of a given node in a binary search tree.
// Return null if there's no "next" node for the given node.
// Example 1:
// Input: root = [2,1,3], p = 1
// 2
// / \
// 1 3
// Output: 2
// Example 2:
// Input: root = [5,3,6,2,4,null,null,1], p = 6
// 5
// / \
// 3 6
// / \
// 2 4
// /
// 1
// Output: null
import "fmt"
// Definition for a binary tree node.
type TreeNode struct {
Val int
Left *TreeNode
Right *TreeNode
}
/**
* Definition for a binary tree node.
* type TreeNode struct {
* Val int
* Left *TreeNode
* Right *TreeNode
* }
*/
func inorderSuccessor(root *TreeNode, p *TreeNode) *TreeNode {
found := false
var res *TreeNode;
var dfs func(node *TreeNode, p *TreeNode)
dfs = func(node *TreeNode, p *TreeNode) {
if node == nil { return }
dfs(node.Left, p)
if found && res == nil {
res = node
return // 找到下一个节点, 直接返回
} else if node.Val == p.Val { // 找到了
found = true
}
dfs(node.Right, p)
}
dfs(root, p)
return res
}
func inorderSuccessor1(root *TreeNode, p *TreeNode) *TreeNode {
var last, res *TreeNode
var dfs func(node *TreeNode)
dfs = func(node *TreeNode) {
if node == nil { return }
dfs(node.Left)
if last == p && res == nil {
res = node
return
}
last = node
dfs(node.Right)
return
}
dfs(root)
return res
}
func main() {
// Example 1:
// Input: root = [2,1,3], p = 1
// 2
// / \
// 1 3
// Output: 2
tree1 := &TreeNode {
2,
&TreeNode{1, nil, nil, },
&TreeNode{3, nil, nil, },
}
fmt.Println(inorderSuccessor(tree1, &TreeNode{1, nil, nil, })) // &{2 0xc000110048 0xc000110060}
// Example 2:
// Input: root = [5,3,6,2,4,null,null,1], p = 6
// 5
// / \
// 3 6
// / \
// 2 4
// /
// 1
// Output: null
tree2 := &TreeNode {
5,
&TreeNode{3, &TreeNode{2, &TreeNode{1, nil, nil, }, nil, }, &TreeNode{4, nil, nil, }, },
&TreeNode{6, nil, nil, },
}
fmt.Println(inorderSuccessor(tree2, &TreeNode{6, nil, nil, })) // <nil>
fmt.Println(inorderSuccessor1(tree1, &TreeNode{1, nil, nil, })) // &{2 0xc000110048 0xc000110060}
fmt.Println(inorderSuccessor1(tree2, &TreeNode{6, nil, nil, })) // <nil>
}