-
Notifications
You must be signed in to change notification settings - Fork 22
/
Copy path3665.inorder-successor-in-bst-ii.cpp
88 lines (85 loc) · 1.64 KB
/
3665.inorder-successor-in-bst-ii.cpp
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
// Tag: Binary Tree, Binary Search Tree
// Time: O(H)
// Space: O(1)
// Ref: Leetcode-510
// Note: -
// There exists a binary search tree, and the binary tree node holds its parent node `parent`.
//
// In this question, you will get **any** node of the binary search tree.
// You need to return the node after this node in the inorder traversal order, or *null* if there is no successor node.
//
// **Example 1**
//
// Input:
//
// ```plaintext
// {2, 1, 3}
// 1
// ```
//
// Output:
//
// ```plaintext
// 2
// ```
//
// Explanation:
//
// A binary search tree looks like this:
//
// ```plaintext
// 2
// / \
// 1 3
// ```
//
// Obviously node 1's inorder successor node is 2.
//
// **Example 2**
//
// Input:
//
// ```plaintext
// {2, 1, 3}
// 3
// ```
//
// Output:
//
// ```plaintext
// null
// ```
//
//
/**
* Definition of ParentTreeNode:
* class ParentTreeNode {
* public:
* int val;
* ParentTreeNode *parent, *left, *right;
* }
*/
class Solution {
public:
/**
* @param node: random node in binary search tree
* @return: the inorder successor of current node
*/
ParentTreeNode* inorderSuccessor(ParentTreeNode *node) {
// write your code here
if (node->right) {
ParentTreeNode *cur = node->right;
while (cur->left) {
cur = cur->left;
}
return cur;
} else {
ParentTreeNode *cur = node->parent;
while (cur && cur->left != node) {
node = cur;
cur = cur->parent;
}
return cur;
}
}
};