问题
I have trouble with a task to find a parent of a specific node in a binary search tree. The solution should be straightforward, but I don't know why my code is not working...I tried different approaches and also searched on the web for any solutions but found nothing. I appreciate any help!!
typedef struct Treenode{
int key;
struct Treenode* lChild;
struct Treenode* rChild;
}node;
node * getParent(node *root, int key){
if (root == NULL) return NULL;
else if (root->rChild->key == key || root->lChild->key == key) return root;
else if (root->key > key) getParent(root->lChild, key);
else getParent(root->rChild, key);
return root;
}
回答1:
else if (root->key > key) getParent(root->lChild, key);
else getParent(root->rChild, key);
In these two cases, you should just return getParent(...);
. Otherwise the result of recursive call is simply dropped.
回答2:
You have to return value of function to a node p, let say as it is of type node*, otherwise the code would not be able to return anything.
来源:https://stackoverflow.com/questions/29579862/find-parent-of-node-in-binary-search-tree