-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path_448_InorderSuccessorInBST.cpp
More file actions
53 lines (44 loc) · 1.09 KB
/
Copy path_448_InorderSuccessorInBST.cpp
File metadata and controls
53 lines (44 loc) · 1.09 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
/* Source - https://www.lintcode.com/problem/inorder-successor-in-bst/description/
Author - Shivam Arora
*/
#include <bits/stdc++.h>
using namespace std;
struct TreeNode {
int data;
TreeNode *left, *right;
TreeNode (int x) {
data = x;
left = right = NULL;
}
};
void insert (TreeNode** root_ref, int x) {
if (*root_ref == NULL) *root_ref = new TreeNode(x);
else {
if (x <= (*root_ref)->data) insert(&((*root_ref)->left), x);
else insert(&((*root_ref)->right), x);
}
}
TreeNode* inorderSuccessor (TreeNode* root, TreeNode* n) {
TreeNode *curr = root, *succ = NULL;
while (curr != NULL) {
if (curr->data > n->data) {
succ = curr;
curr = curr->left;
}
else curr = curr->right;
}
return succ;
}
int main()
{
TreeNode *root = NULL;
insert(&root, 20);
insert(&root, 8);
insert(&root, 22);
insert(&root, 4);
insert(&root, 12);
insert(&root, 10);
insert(&root, 14);
root = inorderSuccessor(root, root->left->right);
cout<<root->data<<endl;
}