二叉搜索树的输出不正确

时间:2017-09-09 17:30:08

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

我已经调试了代码,但没有发现任何错误。下面的代码不会打印二叉搜索树(BST)的所有数据。只有根节点和最后两个节点才能在顺序遍历中显示。

struct node{
    int key;
    node *left;
    node *right;
};

node* newNode(int data){
    node *ptr=new node;
    ptr->key=data;
    ptr->left=ptr->right=NULL;

    return ptr;
}

node* insert_node(node* root,int data){
    if(root==NULL){
        root=newNode(data);
    }else if(data<=root->key){
        root->left=newNode(data);
    }else{
        root->right=newNode(data);
    }

   return root;
}

void inorder(node* root){
    if(root==NULL)
        return;
    inorder(root->left);
    cout<<root->key<<" ";
    inorder(root->right);
}

int main(){
    node *root=NULL;

    root=insert_node(root,10);
    root=insert_node(root,12);
    root=insert_node(root,15);
    root=insert_node(root,1);
    root=insert_node(root,20); 

    inorder(root);

  return 0;
}

1 个答案:

答案 0 :(得分:0)

insert函数没有任何可以找到叶节点的递归或迭代实现。因此新节点将替换根节点的子节点。我认为在评论部分中非常突出了这一点。

这是一个代码块,其中叶节点通过迭代定位,然后插入新节点。

node *insert_node( node *root, int data){
struct node *ptr, *nodeptr, *parentptr;
ptr = (struct node*)malloc(sizeof(struct node));
ptr->data = data;
ptr->left = NULL;
ptr->right = NULL;
if(root==NULL) //tree is empty
{
    root=ptr;
    root->left=NULL;
    root->right=NULL;
}
else
{
    parentptr=NULL; // keep the address of parent node
    nodeptr=root;
    while(nodeptr!=NULL)
    {
        parentptr=nodeptr;
        if(data<nodeptr->data)
            nodeptr=nodeptr->left;
        else
            nodeptr = nodeptr->right;
    }
    // now the parentptr contains address of the leaf node 
    if(data<parentptr->data)
        parentptr->left = ptr;
    else
        parentptr->right = ptr;
}
return root;
}

你也可以参考其他一些来源来递归实现它。

相关问题