C 在二叉搜索树中查找节点的父节点

C 在二叉搜索树中查找节点的父节点,c,binary-search-tree,parent,C,Binary Search Tree,Parent,我在二叉搜索树中查找特定节点的父节点时遇到困难。解决方案应该很简单,但我不知道为什么我的代码不起作用……我尝试了不同的方法,也在网上搜索了任何解决方案,但什么也没找到。谢谢你的帮助 typedef struct Treenode{ int key; struct Treenode* lChild; struct Treenode* rChild; }node; node * getParent(node *root, int key){ if (root ==

我在二叉搜索树中查找特定节点的父节点时遇到困难。解决方案应该很简单,但我不知道为什么我的代码不起作用……我尝试了不同的方法,也在网上搜索了任何解决方案,但什么也没找到。谢谢你的帮助

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

在这两种情况下,只需
返回getParent(…)。否则,递归调用的结果将被简单地丢弃。

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

您忘记返回递归调用的结果了!您可能要做的另一件事是删除
return
后面的所有
else
,因为它们没有效果。还需要像
root->rChild&&root->rChild->key==key | root->lChild&&root->lChild->key==key这样的保护,请为您的解决方案添加一些代码以获得更好的帮助。
else if (root->key > key) getParent(root->lChild, key);
else getParent(root->rChild, key);