在二叉树中找到节点的故障函数

问题描述 投票:0回答:1

此功能出问题。应该找到一个具有相同值phone的节点。我认为尝试查找不存在的节点时会出现问题。

这里是:

bst_node* find_node(bstree* bst, unsigned long phone) { 
    bst_node* x = bst->root;

    if(x == NULL)
        return NULL;
    if(x->phone == phone)
        return bst->root;

    while (x->phone != phone && (x->left != NULL && x->right != NULL) ) {
        if(phone <= x->phone) {
            x = x->left;
        } else {
            x = x->right;
        }
    }
    if (x->phone == phone) {
        return x;
    } else {
        return NULL;
    }          
}
c memory-management tree binary-tree binary-search-tree
1个回答
1
投票

基本上,您的问题出在您的while循环中。请记住,您不能保证每个节点都会有两个孩子,某些节点可能只有一个孩子,而您并不是在探索只有一个孩子的那些节点。我下面要做的是将对左右节点是否存在的检查分离为while循环中的条件语句。这使我们可以探索整个树:)我还在while循环中添加了else语句,因为如果节点没有子节点,那么我们已经完成了探索,节点无法进入树中。

bst_node* find_node(bstree* bst, unsigned long phone) {

    bst_node* x = bst->root;
    if(x == NULL)
        return NULL;
    if(x->phone == phone)
        return bst->root;
    while (x->phone != phone){
        if(phone <= x->phone && x->left != NULL){
             x = x->left;
        }
        else if (phone > x->phone && x->right != NULL){
             x = x->right;
        }
        else {return NULL;}
    return x;

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