BST insert value

BST insert value

本文关键字:value insert BST      更新时间:2023-10-16

我很难让插入功能正常工作。cout 语句与我作业的语句不匹配。如果我尝试插入 5,我会得到inserted: 5 right child of: 3但应该是inserted: 5 right child of: 22 有人可以帮助我吗?

Node* insert(Node *root, int value){
Node *tmp = root;
while(tmp != NULL){
    if (tmp->key == value){
        return tmp;
    }
    else if (value > tmp->key){
        Node *tm = new Node(NULL, NULL, NULL);
        tm->key = value;
        tm->left = tmp->right;
        tm->right = tmp->left;
        tmp->right = tm;
        cout << "inserted: " << tm->key << " right child of: " << tmp->key <<endl;
        tmp = tmp->right;
    }
    else if (value < tmp->key){
        Node *tm = new Node(NULL, NULL, NULL);
        tm->key = value;
        tm->left = NULL;
        tm->right = NULL;
        tmp->left = tm;
        cout << "inserted: " << tm->key << " left child of: " << tmp->key <<endl;
        tmp = tmp->left;
    }
}
return tmp;

}

您的插入代码存在一些问题:

  • 始终将新节点作为根的子节点插入(这并不总是产生 BST)
  • 当您链接树时,您要么(如果您放置为右子级)使根的左子级也成为新节点的左子级,要么(如果左子级)失去对根的原始左子树的跟踪。
  • 如果根NULL会发生什么

以下代码应该适合您

//The following code assumes the following definition of Node
struct Node {
  Node(int val, Node* l, Node* r):key(val),left(l),right(r){}
  int key;
  Node* left;
  Node* right;
}
// Returns the root of the tree after inserting val into tree (no duplicates)
Node * insert (Node * root, int val){
  if (root == NULL) return new Node(val, NULL, NULL);
  if (root->key == val) return root;
  if (root->key > val) return insert(root->left, val);
  return insert(root->right, val);
}

上面的代码以递归方式定义插入。基本情况:树为空。插入新值作为根。如果根是键,那么您就完成了(没有重复的键)。否则,将值插入到左侧或右侧子树中(如果值小于 root->key 则向左插入,否则插入到右侧)。

或者,您可以使用 while 循环以迭代方式定义插入。

Node * insert (Node * root, int val){
  // is this an empty tree?
  if (root == NULL) return new Node(val, NULL, NULL);
  Node* tmp = root;
  while (tmp != null){
    if (tmp->key == val) break;
    if (tmp->key > val){
      if (tmp->left == NULL){
        tmp->left = new Node(val, NULL, NULL);
        break;
      } else {
        tmp = tmp->left;
      }
    } else {
      if (tmp->right == NULL){
        tmp->right = new Node(val, NULL, NULL);
        break;
      } else {
        tmp = tmp->right;
      }
    }
  }
  return root;
}

无论哪种情况,您都可以以相同的方式使用插入。

Node * tree1 = NULL;
tree1 = insert(tree1, 3);
tree1 = insert(tree1, 1);
tree1 = insert(tree1, 2);
tree1 = insert(tree1, 4);

后面tree1将是下一棵树。

  3
 / 
1   4
 
  2