-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathinordersuccessor.cpp
More file actions
95 lines (84 loc) · 1.94 KB
/
inordersuccessor.cpp
File metadata and controls
95 lines (84 loc) · 1.94 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
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
#include <bits/stdc++.h>
using namespace std;
class BinaryTree
{
public:
int value;
BinaryTree*left;
BinaryTree*right;
BinaryTree(int value){
this->value = value;
left = nullptr;
right = nullptr;
}
};
BinaryTree*leftMostNode(BinaryTree*node)
{
while (node != NULL && node->left != NULL)
node = node->left;
return node;
}
BinaryTree*rightMostNode(BinaryTree*node)
{
while (node != NULL && node->right != NULL)
node = node->left;
return node;
}
BinaryTree*findInorderRec(BinaryTree*root,BinaryTree*node)
{
if(root == NULL)
{
return NULL;
}
BinaryTree*temp;
if(root == node || temp = findInorderRec(root->left,node) || temp = findInorderRec(root->right,node))
{
if(temp!=NULL)
{
if(root->left == temp)
{
return root->data;
}
}
return root;
}
}
BinaryTree*findSuccesor(BinaryTree*root,BinaryTree*node)
{
if(root==NULL || node == NULL)
{
return NULL;
}
if(node->right!=NULL)
{
return leftMostNode(node->right);
}
else
{
if(node->right==NULL)
{
BinaryTree*rightmost = rightMostNode(root);
// IF NODE IS THE RIGHT MOST CHILD
if(rightmost == node)
{
return NULL;
}
else
{
return findInorderRec(root,node);
}
}
}
}
int main() {
BinaryTree*root = new BinaryTree(1);
root->left = new BinaryTree(2);
root->right = new BinaryTree(3);
root->left->left = new BinaryTree(4);
root->left->right = new BinaryTree(5);
root->right->right = new BinaryTree(6);
// root->right->right = new BinaryTree(7);
// root->left->left->left = new BinaryTree(8);
// root->left->left->right = new BinaryTree(9);
cout<<findSucessor(root,root->left->right);
}