File tree 1 file changed +64
-0
lines changed
go-leetcode/classify_algorithm/tree/leetcode_0285_inorder-successor-in-bst
1 file changed +64
-0
lines changed Original file line number Diff line number Diff line change
1
+ package leetcode_0285_inorder_successor_in_bst
2
+
3
+ // 0285. 二叉搜索树中的中序后继
4
+ // https://leetcode.cn/problems/inorder-successor-in-bst/
5
+
6
+ type TreeNode struct {
7
+ Val int
8
+ Left * TreeNode
9
+ Right * TreeNode
10
+ }
11
+
12
+ // inorderSuccessor dfs
13
+ // 时间复杂度: O(n)
14
+ // 空间复杂度: O(n)
15
+ func inorderSuccessor (root * TreeNode , p * TreeNode ) * TreeNode {
16
+ find := false
17
+ var (
18
+ ans * TreeNode
19
+ dfs func (root * TreeNode )
20
+ )
21
+ dfs = func (root * TreeNode ) {
22
+ // ans != nil 表示如果找到结果就提前结束
23
+ if root == nil || ans != nil {
24
+ return
25
+ }
26
+ dfs (root .Left )
27
+ if find && ans == nil {
28
+ ans = root
29
+ }
30
+ if root .Val == p .Val && ! find {
31
+ find = true
32
+ }
33
+ dfs (root .Right )
34
+ }
35
+ dfs (root )
36
+ return ans
37
+ }
38
+
39
+ // inorderSuccessor_2 bfs
40
+ // 时间复杂度: O(n)
41
+ // 空间复杂度: O(n)
42
+ func inorderSuccessor_2 (root * TreeNode , p * TreeNode ) * TreeNode {
43
+ var (
44
+ stack []* TreeNode
45
+ pre * TreeNode
46
+ cur = root
47
+ )
48
+
49
+ for cur != nil || len (stack ) > 0 {
50
+ // 遍历左节点
51
+ for cur != nil {
52
+ stack = append (stack , cur )
53
+ cur = cur .Left
54
+ }
55
+ cur = stack [len (stack )- 1 ]
56
+ stack = stack [:len (stack )- 1 ]
57
+ if pre == p {
58
+ return cur
59
+ }
60
+ pre = cur
61
+ cur = cur .Right
62
+ }
63
+ return nil
64
+ }
You can’t perform that action at this time.
0 commit comments