在二叉树中更改父子位置

时间:2014-01-03 16:37:24

标签: c tree binary-tree

所以,我想要做的是检查一个完整的二叉树叶子中的int是否大于它的父亲的int,并使用它作为一个标准,它将它的父亲一直改变到根目录。问题是,当它必须与根比较和改变位置时,它会发生段错误;如果我在此之前停止循环,它的工作正常(我认为)。我错过了一些明显的东西吗?

typedef struct tnode *Treeptr;

typedef struct tnode {
    float owed;
    long afm;   

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

添加新叶时会发生以下情况。我已经省略了叶子实际添加到树中的部分,因为它工作正常并且非常冗长。指针p指向循环开始之前插入的最后一个叶子。 root的父亲和叶子的子节点被初始化为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;
}

1 个答案:

答案 0 :(得分:1)

i=1的情况下,p指向根节点,而p-&gt;父可以是野指针或未初始化的指针。 所以,当你执行行

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

p-&gt;父亲无法解除引用,并会显示分段错误。

我认为将行更改为

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

将解决它。

相关问题