有序二进制树插入

时间:2011-06-06 01:55:58

标签: c algorithm binary-tree

我在下面的代码中遇到了问题,它是有序二叉树程序的一部分。问题是,当我在输入中输入数字时,一些元素就会丢失,并且它会一直发生。我查看了代码,无法弄清楚为什么会这样。你能帮我解决这个问题吗?感谢。

void insert_ord(int number, struct treenode *currentNode){
   if(currentNode->flag == 0){
      currentNode->number = number;
      currentNode->flag = 1;                  
   }
   else{
      if(number <= currentNode->number){
         if(currentNode->left != NULL) insert_ord(number, currentNode->left);
         else {
            struct treenode *store = (struct treenode *)malloc(sizeof(struct treenode));
            currentNode->left = store;
            store->number = number;
            store->left = store->right = NULL;
            store->prev = currentNode;
         }
      }
      if(number > currentNode->number){
         if(currentNode->right != NULL) insert_ord(number, currentNode->right);
         else {
            struct treenode *store = (struct treenode *)malloc(sizeof(struct treenode));
            currentNode->right = store;
            store->number = number;
            store->left = store->right = NULL;
            store->prev = currentNode;
         }
      }
   }
}

2 个答案:

答案 0 :(得分:2)

您没有为新插入的节点设置store->flag。大概应该设置为1。

您还应该重新构建代码,以便不重复创建新节点 - 使用当前代码执行此操作的最简单方法是将其分离为新函数:

struct treenode *new_node(struct treenode *parent, int number)
{
    struct treenode *store = malloc(sizeof(struct treenode));

    if (store) {
        store->number = number;
        store->left = store->right = NULL;
        store->prev = parent;
        store->flag = 1;
    }

    return store;
}

然后您的插入代码变为:

if (currentNode->left)
    insert_ord(number, currentNode->left);
else
    currentNode->left = new_node(currentNode, number);

(和右侧节点类似)。

答案 1 :(得分:0)

malloc返回未初始化的内存,而您没有初始化malloc结构的flag字段。