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

问题描述 投票:2回答:2

我在查找二叉搜索树中特定节点的父节点时遇到问题。解决方案应该是直截了当的,但我不知道为什么我的代码不起作用...我尝试了不同的方法,并在网上搜索任何解决方案,但没有找到任何结果。我感谢任何帮助!!

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;
}
c binary-search-tree parent
2个回答
4
投票
else if (root->key > key) getParent(root->lChild, key);
else getParent(root->rChild, key);

在这两种情况下,你应该只是return getParent(...);。否则,简单地删除递归调用的结果。


0
投票

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

© www.soinside.com 2019 - 2024. All rights reserved.