更改二叉树中父亲和 child 的位置

标签 c tree binary-tree

所以,我想做的是检查一个完整的二叉树叶子中的 int 是否大于它的父亲,并以此为标准让它不断地改变它的父亲的位置,一直到根。问题是,当它必须与根进行比较和更改位置时,它会出现段错误;如果我在那之前让循环停止,它就可以正常工作(我认为)。我在这里遗漏了什么明显的东西吗?

typedef struct tnode *Treeptr;

typedef struct tnode {
    float owed;
    long afm;   

    Treeptr father;
    Treeptr left;
    Treeptr right;
} Treenode;

添加新叶子时会发生以下情况。我省略了叶子实际添加到树中的部分,因为它工作正常并且非常冗长。指针 p 指向循环开始前插入的最后一片叶子。根的父亲和叶子的 child 被初始化为 NULL。

static int depth = 1;       
static int nodes_number = 0;        
int i;
Treeptr temp, temp2;

if(nodes_number == pow(2, depth) - 1)  
    depth++;            
nodes_number++; 

for(i=1 ; i<depth ; i++) {      
    if(p->owed > p->father->owed) { 
        temp = p->father;
        p->father = temp->father;
        if(temp->father != NULL) {
            if(temp == temp->father->left)
                temp->father->left = p;
            else
                temp->father->right = p;
        }   
        if(p == temp->left) {
            temp->left = p->left;
            p->left = temp;
            temp2 = p->right;
            p->right = temp->right;
            temp->right = temp2;                
        }
        else {
            temp->right = p->right;
            p->right = temp;
            temp2 = p->left;
            p->left = temp->left;
            temp->left = temp2;
        }           
    }
    else
        break;
}

最佳答案

i=1的情况下,p指向根节点,p->father可能是野指针或未初始化指针。 因此,当您执行该行时

if(p->owed > p->father->owed) { 

p->父亲不能取消引用,将显示段错误。

我想把行改成

if( (p->father!=NULL) && (p->owed > p->father->owed) ) { 

会解决的。

关于更改二叉树中父亲和 child 的位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20908423/

相关文章:

c++ - 指针错误

c - MSVS 2015 将 errno 放入 stddef.h?

c程序输出说明

f# - 在 f# 中折叠/递归多路树

python - 将postgresql数据库表转换为json树python

algorithm - 无线程二叉搜索树的中序遍历,没有堆栈

c - 节目结束前暂停

c - 将数组作为参数传递的问题

c - 在 "in-order tree traversal"中查找特定节点

c++ - 该算法用于查找所有路径总和的时间复杂度是多少?