简体   繁体   English

二进制搜索树,无法遍历

[英]Binary Search Tree, cannot do traversal

Please see BST codes below. 请参阅下面的BST代码。 It only outputs "5". 它仅输出“ 5”。 what did I do wrong? 我做错了什么?

#include <iostream>

class bst {
 public:
  bst(const int& numb) : root(new node(numb)) {}

  void insert(const int& numb) {
    root->insert(new node(numb), root);
  }

  void inorder() {
    root->inorder(root);
  }

 private:
  class node {
   public:
    node(const int& numb) : left(NULL), right(NULL) {
      value = numb;
    }

    void insert(node* insertion, node* position) {
      if (position == NULL) position = insertion;
      else if (insertion->value > position->value)
        insert(insertion, position->right);
      else if (insertion->value < position->value)
        insert(insertion, position->left);
    }

    void inorder(node* tree) {
      if (tree == NULL)
        return;
      inorder(tree->left);
      std::cout << tree->value << std::endl;
      inorder(tree->right); 
    }
  private:
    node* left;
    node* right;
    int value;
  };

  node* root;
};

int main() {
  bst tree(5);
  tree.insert(4);
  tree.insert(2);
  tree.insert(10);
  tree.insert(14);
  tree.inorder();
  return 0;
}

use reference: 使用参考:

void insert(node* insertion, node* &position) void insert(node *插入,node *和位置)

void inorder(node* &tree) { void inorder(node *&tree){

It's because you never set the values of the left and right fields of root . 这是因为您从未设置rootleftright字段的值。

Somewhere you have to say, for a given node, n : 对于某个给定的节点,您必须在某个地方说n

n->left = ...
n->right = ...

You never did this. 你从来没有这样做。 So you ended up with a single node tree. 因此,您最终得到了一个单节点树。 Your root has two null children. 您的根有两个空子代。

You can get sneaky about this, too: if you do what @user1431015 suggests, and pass the child pointers by reference, then the assignment to the reference paraemter ( position ) will do the trick. 您也可以偷偷摸摸:如果您按照@ user1431015的建议进行操作,并通过引用传递子指针,则对引用参数( position )的赋值将达到目的。 Passing them by value, as you did, only assigns to a local variable, and not to the tree itself. 和您一样,按值传递它们仅分配给局部变量,而不分配给树本身。

Your insert never ends up doing anything in most cases. 在大多数情况下,插入都永远不会做任何事情。 The base case of your recurstion is: 递归的基本情况是:

void insert(node* insertion, node* position) {
     if (position == NULL) position = insertion;

But all 'position' is is a locally scoped pointer value. 但是所有的“位置”都是本地范围的指针值。 Assigning to it will have no effect once your function exits. 函数退出后,对其进行分配将无效。

What you need to do is make the position parameter a reference to pointer. 您需要做的是使position参数成为指针的引用 IN other words, make it of type node*& . 换句话说,使其类型为node*& Then the assignment will stick after you exit the function. 然后,该功能将在退出功能后保留。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM