简体   繁体   English

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

[英]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(...); 在这两种情况下,您应该只return getParent(...); . Otherwise the result of recursive call is simply dropped. 否则,将仅丢弃递归调用的结果。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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