void inorderPredecessor(Node* root, Node* &pre,int key){
if(root == NULL ) return ;
if(root -> data == key){
inorderPredecessor(root ->left , pre , key);
}else if(root -> data > key){
inorderPredecessor(root -> left ,pre ,key);
}else{
if(pre == NULL)
pre = root;
else if(pre -> data > root -> data)
pre = root;
inorderPredecessor(root -> right , pre ,key);
}
}
if, you can highlight the mistake or where this approach goes wrong, much thanks!
I started this approach with the thought of,
- if the node u are on is equal to target node,
call for left nodes, as they are less than target node. - if node u are on is greater than the target node,
again , call for left nodes to find the target node. - and if node u are on is less than the target node,
check the node data and the “pre” variable if it is null, then set pre equal to current node,
if not, then compare both values and the smaller one is kept.
I dry run it quite a few times, i couldn’t find the mistake i was making.
New contributor
Abhinav Mishra is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.