【问题标题】:What's wrong with this code for BST insertion?这段 BST 插入代码有什么问题?
【发布时间】:2017-04-16 23:07:02
【问题描述】:

所以我为在 BST(二叉搜索树)中插入节点编写了这段代码,但程序总是打印出树是空的。我想我所做的函数调用有问题。你能解释一下这个问题吗?

    #include <bits/stdc++.h>
    #include <conio.h>
    using namespace std;

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


    void insert(node* root, int item)
    {
        if(root == NULL)
        {
            node* temp = new node();
            temp->key = item;
            temp->left = NULL;
            temp->right = NULL;
            root = temp;
        }
        else
        {
            if((root->key)>item)
            {
                insert(root->left,item);
            }
            else 
            {
                insert(root->right,item);
            }
        }
    }

    void inorder(node* root)
    {
        if(root!=NULL)
        {
            inorder(root->left);
            cout<<" "<<root->key<<" ";
            inorder(root->right);
        }
        else cout<<"The tree is empty.";
    }

    int main()
    {
        // cout<<endl<<" Here 5 ";
        node* root = NULL;
        int flag = 1 , item;
        while(flag == 1)
        {
            cout<<"Enter the number you want to enter : ";
            cin>>item;
            // cout<<endl<<" Here 6";
            insert(root, item);
            cout<<"Do you want to enter another number (1 -> YES)?";
            cin>>flag;
        }
        cout<<"The final tree is :";
        inorder(root);
        getch();
        return 0;
    }

【问题讨论】:

  • node* root; 中有一个未初始化的指针。除非您为其分配该值,否则它不会设置为 NULL。
  • 我将其更改为 NULL。还有一个问题是输出总是:“树是空的,”
  • 下一个问题是将node指针按值传递给insert。这意味着对指针的任何更改都是该函数的本地更改,并且不会影响 main 中的指针。

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


【解决方案1】:

首先,插入有点不正确。根指针必须通过引用传递。只是一些,例如:

void insert(node *& root, int item)
{
  if(root == NULL)
    {
      node* temp = new node();
      temp->key = item;
      temp->left = NULL;
      temp->right = NULL;
      root = temp;
    }
  else
    {
      if ((root->key) > item)
        {
          insert(root->left,item);
        }
      else 
        {
          insert(root->right,item);
        }
    }
}

在结构上与您的代码相同(除了对根的引用)

此外,您的中序遍历很奇怪,因为它会打印出消息“树为空”。每次遍历检测到一个空节点。我会这样修改:

void inorder(node* root)
{
  if (root == NULL)
    return;

  inorder(root->left);
  cout<<" "<<root->key<<" ";
  inorder(root->right);
}

最后,我会稍微修改main() 以管理树为空时的情况(而不是在中序遍历中进行):

int main()
{
  node* root = NULL;
  int flag = 1 , item;
  while(flag == 1)
    {
      cout<<"Enter the number you want to enter : ";
      cin>>item;
      insert(root, item);
      cout<<"Do you want to enter another number (1 -> YES)?";
      cin>>flag;
    }
  cout<<"The final tree is :";
  if (root == NULL)
    cout << "The tree is empty.";
  else
    inorder(root);
  cout << endl;
  return 0;
}

【讨论】:

    猜你喜欢
    • 2015-04-25
    • 2018-09-09
    相关资源
    最近更新 更多