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

标签 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 == 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);

在这两种情况下,您应该返回 getParent(...);。否则递归调用的结果将被简单地丢弃。

关于c - 在二叉搜索树中查找节点的父节点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29579862/

相关文章:

c - 头文件中的结构在源文件中产生错误

c - C 中箭头运算符 (->) 的用法

java - BST 相等性检查

c++ - 在哪里实现堆栈类(用于非递归二进制搜索函数)

css - 将父级悬停在当前父级 css 之外

c - 为什么父进程在处理信号后没有返回到确切的位置?

c - 我需要帮助将文件分块输入到 mmap

c - 为什么没有无符号最小值?

python - 查找二叉搜索树的最小共同祖先时出错

jsf - <f :setPropertyActionListener> Parent is not of type ActionSource