Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commitff6e838

Browse files
Add files via upload
1 parentbdb2def commitff6e838

File tree

1 file changed

+105
-0
lines changed

1 file changed

+105
-0
lines changed

‎inorder_succcessor.cpp‎

Lines changed: 105 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,105 @@
1+
//BST to Linked List
2+
#include<iostream>
3+
usingnamespacestd;
4+
5+
classNode
6+
{
7+
public:
8+
int key;
9+
Node *left;
10+
Node *right;
11+
12+
Node(int key){
13+
this->key = key;
14+
left = right =NULL;
15+
}
16+
};
17+
18+
Node*insert(Node * root,int key){
19+
if(root==NULL){
20+
returnnewNode(key);
21+
}
22+
23+
//rec case
24+
if(key < root->key){
25+
root->left =insert(root->left,key);
26+
}
27+
else{
28+
root->right =insert(root->right,key);
29+
}
30+
return root;
31+
32+
}
33+
34+
35+
36+
voidprintInOrder(Node *root){
37+
if(root==NULL){
38+
return;
39+
}
40+
//left, root, right
41+
printInOrder(root->left);
42+
cout << root-> key <<" ,";
43+
printInOrder(root->right);
44+
}
45+
46+
47+
//---------Next Inorder Successor
48+
49+
Node *inorderSucc(Node * root, Node * target){
50+
51+
// If Right Subtree
52+
if(target->right!=NULL){
53+
Node* temp = target->right;
54+
while(temp->left!=NULL){
55+
temp = temp->left;
56+
}
57+
return temp;
58+
}
59+
60+
61+
// Otherwise
62+
Node * temp = root;
63+
Node * succ =NULL;
64+
65+
while (temp!=NULL){
66+
67+
if(temp->key > target->key){
68+
succ = temp;
69+
temp = temp->left;
70+
}
71+
elseif(temp->key < target->key ){
72+
temp = temp->right;
73+
}
74+
else{
75+
break;
76+
}
77+
}
78+
return succ;
79+
}
80+
81+
82+
intmain(){
83+
84+
Node * root =NULL;
85+
root =insert(root,8);
86+
root =insert(root,3);
87+
root =insert(root,10);
88+
root =insert(root,1);
89+
root =insert(root,6);
90+
root =insert(root,14);
91+
root =insert(root,4);
92+
root =insert(root,7);
93+
root =insert(root,13);
94+
95+
//Test our Code
96+
Node* t1 = root->left->right->right;
97+
Node* t2 = root->right;
98+
99+
cout<<"Inorder succ of 7 is" <<inorderSucc(root,t1)->key <<endl;
100+
cout<<"Inorder succ of 10 is" <<inorderSucc(root,t2)->key <<endl;
101+
102+
103+
104+
return0;
105+
}

0 commit comments

Comments
 (0)

[8]ページ先頭

©2009-2025 Movatter.jp