-
Notifications
You must be signed in to change notification settings - Fork 22
/
Copy path448.inorder-successor-in-bst.cpp
106 lines (95 loc) · 2.47 KB
/
448.inorder-successor-in-bst.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
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
// Tag: Binary Tree, Binary Search Tree
// Time: O(H)
// Space: O(1)
// Ref: Leetcode-285
// Note: Successor
// Given a binary search tree ([See Definition](http://www.lintcode.com/problem/validate-binary-search-tree/ "BST")) and a node in it, find the in-order successor of that node in the BST.
//
// If the given node has no in-order successor in the tree, return `null`.
//
// **Example 1:**
//
// ```
// Input: {1,#,2}, node with value 1
// Output: 2
// Explanation:
// 1
// \
// 2
// ```
//
// **Example 2:**
//
// ```
// Input: {2,1,3}, node with value 1
// Output: 2
// Explanation:
// 2
// / \
// 1 3
// ```
//
// [Binary Tree Representation](https://www.lintcode.com/help/binary-tree-representation/)
//
// It's guaranteed *p* is one node in the given tree. (You can directly compare the memory address to find p)
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
/*
* @param root: The root of the BST.
* @param p: You need find the successor node of p.
* @return: Successor of p.
*/
TreeNode * inorderSuccessor(TreeNode * root, TreeNode * p) {
// write your code here
TreeNode *node = root;
TreeNode *next = nullptr;
while (node) {
if (p->val < node->val) {
next = node;
node = node->left;
} else {
node = node->right;
}
}
return next;
}
};
class Solution {
public:
/*
* @param root: The root of the BST.
* @param p: You need find the successor node of p.
* @return: Successor of p.
*/
TreeNode * inorderSuccessor(TreeNode * root, TreeNode * p) {
// write your code here
stack<TreeNode *>st;
TreeNode *cur = root;
bool find = false;
while (!st.empty() || cur) {
while (cur) {
st.push(cur);
cur = cur->left;
}
cur = st.top();
st.pop();
if (find) {
return cur;
}
if (cur == p) {
find = true;
}
cur = cur->right;
}
return nullptr;
}
};