Find parent of node in binary search tree

旧巷老猫 提交于 2019-12-11 03:34:30

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!