二进制搜索树显示为空

时间:2018-11-25 18:40:08

标签: c++ binary-search-tree

struct node
{
   int data;
   node *left,*right;
};

  class bst
 {
 public:
    node *root;
    bst(){root = NULL;}
   void bst_insert(node*,int);
   void inorder(node*);
   };


void bst::bst_insert(node* x, int d) {
   if (x== NULL) {
      node* tmp = new node;
      tmp->data = d;
      tmp->left = NULL;
      tmp->right = NULL;
      x= tmp;
   }
   else if (d <= x->data)
      bst_insert(x->left,d);
   else
      bst_insert(x->right,d);
}

void bst::inorder(node* x) {
   if(x != NULL) {
      inorder(x->left);
      cout << x->data << " ";
      inorder(x->right);
   }
}

int main() {
   bst b;
   b.bst_insert(b.root,3);
   b.bst_insert(b.root,2);
   b.inorder(b.root);
}

bst是具有节点root *根的类(在构造函数上初始化为null)

二分搜索树的显示顺序始终显示为空。

代码有什么问题?

代码看起来不错,但是总是bst没有值并且总是显示为空,而root为null !!!

1 个答案:

答案 0 :(得分:0)

任何地方都没有代码将root设置为NULL以外的任何其他值。当您呼叫inorder时,由于rootNULL,因此它什么也不做。

b.bst_insert(b.root,3);

由于root首先是NULL,所以等效于:

b.bst_insert(NULL,3);

这不会将新创建的节点附加到任何东西上。

相关问题