For Seg fault, you should check whether temp
is null
, as you code might pass temp->right
and temp->left
to it, which might be null
.
if(temp == NULL) return 0; // add this check
But there is another problem in your code: you never reuse the return value. Then it will just iterate. Suppose you would like to return the data stored in the leaf node after your traversal, then the code could look like this:
//Find the in-order successor
int table::in_order_successor(node * root, node * temp) {
if(root == NULL) return 0;
if(temp == NULL) return 0; // add this check
if(root->right != NULL) {
// check by pointer instead of the data unless each
// node->data is unique. Otherwise unwanted moving
// right will occur.
if(root == temp) {
if (temp->right != null) {
// use `return` here instead of plain function call to get
// the update of the rest of the recursion.
return in_order_successor(root, temp->right);
}
}
}
if (temp->left != null) {
// if have left child, return what you will find in the next step
return in_order_successor(root, temp->left); // use return here
} else {
// reach the left-most leaf after first steping right at root node.
return temp->data;
}
}