How to solve the question without recursion?


#1

I know the recursive way of doing this but , can’t figure out how to do it iteratively , any help is appreciated.


#2

TreeNode* findminright(TreeNode* A){
if(A==NULL)
return NULL;
while(A->left!=NULL){
A=A->left;
}
return A;
}

TreeNode* Solution::getSuccessor(TreeNode* A, int B) {
TreeNode* temp=A;
TreeNode* ancestor=NULL;
if(temp==NULL)
return NULL;
while(temp!=NULL){
if(temp->val>B){
ancestor = temp;
temp = temp->left;
}
else if(temp->val<B){
temp = temp->right;
}
else{
if(temp->right!=NULL){
return findminright(temp->right);
}
else{
return ancestor;
}
}
}
return temp;

}


#3

TreeNode* Solution::getSuccessor(TreeNode* A, int k) {
// Do not write main() function.
// Do not read input, instead use the arguments to the function.
// Do not print the output, instead return values as specified
// Still have a doubt. Checkout www.interviewbit.com/pages/sample_codes/ for more details

TreeNode* first_greater = NULL;
TreeNode* subtree = A;
while(subtree){
    if(subtree->val > k){
        first_greater = subtree;
        subtree = subtree->left;
    }
    else{
        subtree = subtree->right;
    }
}
return first;

}