Skip to content

Commit 143a920

Browse files
Create inorder_successor_in_bst.cpp
1 parent d1f3873 commit 143a920

File tree

1 file changed

+35
-0
lines changed

1 file changed

+35
-0
lines changed

inorder_successor_in_bst.cpp

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
/**
2+
* Definition for a binary tree node.
3+
* struct TreeNode {
4+
* int val;
5+
* TreeNode *left;
6+
* TreeNode *right;
7+
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
8+
* };
9+
*/
10+
11+
12+
class Solution {
13+
public:
14+
/*
15+
* @param root: The root of the BST.
16+
* @param p: You need find the successor node of p.
17+
* @return: Successor of p.
18+
*/
19+
20+
TreeNode *successor = nullptr;
21+
TreeNode * inorderSuccessor(TreeNode * root, TreeNode * p) {
22+
// write your code here
23+
24+
if(root == nullptr) {
25+
return nullptr;
26+
}
27+
28+
if(root->val <= p->val) {
29+
return inorderSuccessor(root->right, p);
30+
}
31+
32+
TreeNode *successor = inorderSuccessor(root->left, p);
33+
return successor == nullptr ? root : successor;
34+
}
35+
};

0 commit comments

Comments
 (0)