简体   繁体   中英

Find parent of node in binary search tree

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;
}
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.

您必须将函数的值返回到节点p,假设它是node *类型,否则代码将无法返回任何内容。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM