【问题标题】:Binary Search Tree insertion/traversal not functioning properly二叉搜索树插入/遍历无法正常工作
【发布时间】:2020-07-04 14:04:18
【问题描述】:

我试图通过插入一些元素 (5,8,10,20,30) 来实现 BST,并通过中序遍历打印它们。但输出是:

5 8 30 20 8 30 10 5 8 30 20 8 30

代替:

5 8 10 20 30 

我尝试调试代码,但它似乎在中序遍历部分出现故障,即使它是正确的(在我看来)。

代码如下:

#include<stdio.h>
#include<stdlib.h>

struct tree{
struct tree *lchild, *rchild;
int data;
}*root=NULL;

void insert(int key)
{
struct tree *tail,*new,*temp=root;
if(root==NULL)
{
    new=(struct tree*)malloc(sizeof(struct tree));
    new->data=key;
    new->lchild=new->rchild=NULL;
    root=new;
    return;
}
else{       
    while(temp!=NULL)
    {
        tail=temp;
        if(key<temp->data)
            temp=temp->lchild;
        else if(key>temp->data)
            temp=temp->rchild;
        else
            return;
    }
    new=(struct tree*)malloc(sizeof(struct tree));
    new->data=key;
    new->lchild=new->rchild=NULL;
    
    if(key<tail->data)
        tail->lchild=new;
    tail->rchild=new;
    }

}

void inOrder(struct tree *temp)
{
    if(temp)
    {
    inOrder(temp->lchild);
    printf("%d ",temp->data);
    inOrder(temp->rchild);
    } 
}

int main()
{
insert(10);  
insert(5);
insert(20);
insert(8);
insert(30);

inOrder(root);
return 0;

 }

【问题讨论】:

  • 将您的代码与here显示的代码进行比较。
  • 是的,我之前浏览过这段代码。它使用递归函数进行插入。我正在使用迭代函数。除此之外,代码中几乎所有其他内容都相同。
  • tail-&gt;rchild=new; --->> else tail-&gt;rchild=new;

标签: c binary-tree binary-search-tree


【解决方案1】:

改变


if(key<tail->data)
        tail->lchild=new;
tail->rchild=new;


if (key<tail->data) tail->lchild=new;
else tail->rchild=new;
 

指针对指针的乐趣:


void insert(int key)
{
struct tree **pp, *new;

    for ( pp = &root; *pp ;  ) {
        if (key < (*pp)->data)
            pp = &(*pp)->lchild;
        else if (key > (*pp)->data)
            pp = &(*pp)->rchild;
        else return;
    }

    new = malloc(sizeof *new );
    new->data = key;
    new->lchild = new->rchild = NULL;
    *pp = new;

    return;
}

【讨论】:

    猜你喜欢
    • 2013-11-02
    • 2016-01-21
    • 1970-01-01
    • 1970-01-01
    • 2019-04-09
    • 2016-02-04
    相关资源
    最近更新 更多