-
Notifications
You must be signed in to change notification settings - Fork 243
/
PredecessorAndSuccessor.cpp
104 lines (56 loc) · 1.57 KB
/
PredecessorAndSuccessor.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
// https://www.codingninjas.com/codestudio/problems/_893049?topList=love-babbar-dsa-sheet-problems&leftPanelTab=0
#include <bits/stdc++.h>
/*************************************************************
Following is the Binary Tree node structure
template <typename T>
class BinaryTreeNode
{
public :
T data;
BinaryTreeNode<T> *left;
BinaryTreeNode<T> *right;
BinaryTreeNode(T data) {
this -> data = data;
left = NULL;
right = NULL;
}
~BinaryTreeNode() {
if (left)
{
delete left;
}
if (right)
{
delete right;
}
}
};
*************************************************************/
pair<int,int> predecessorSuccessor(BinaryTreeNode<int>* root, int key)
{
// Write your code here.
BinaryTreeNode<int>* temp= root;
int pre= -1;
int suc= -1;
while(temp!=NULL && temp->data!=key){
if(temp->data>key){
suc= temp->data;
temp= temp->left;
}
else{
pre= temp->data;
temp= temp->right;
}
}
BinaryTreeNode<int>* leftTree= temp->left;
while(leftTree!=NULL){
pre= leftTree->data;
leftTree= leftTree->right;
}
BinaryTreeNode<int>* rightTree= temp->right;
while(rightTree!=NULL){
suc= rightTree->data;
rightTree= rightTree->left;
}
return {pre, suc};
}