二叉树插入算法

Binary Tree Insert Algorithm

本文关键字:算法 插入 二叉树      更新时间:2023-10-16

我最近完成了一个项目的二叉搜索树的实现。一切都很顺利,我学到了很多。然而,现在我需要实现一个常规的二叉树…不知什么原因,这把我难住了。

我正在寻找一种方法来做我的InsertNode函数..

通常在BST中你只需要检查data <根然后插入左,反之亦然。然而,在普通的二叉树中,它只是从左向右填充,一次一层。>

谁能帮我实现一个函数,只是添加一个新的节点到二叉树从左到右,没有特定的顺序?

这是我的插入BST:

void Insert(Node *& root, int data)
{
  if(root == nullptr)
  {
    Node * NN = new Node;
    root = NN;
  }
  else
  {
    if(data < root->data)
    { 
      Insert(root->left, data);
    }
    else
    {
      Insert(root->right, data);
    }
  }
}

我知道这是一个前段时间发布的问题,但我仍然想分享我对它的看法。

我要做的(因为这确实没有很好地记录)是使用广度优先搜索(使用队列)并将子节点插入到我遇到的第一个null中。这将确保你的树在进入另一个关卡之前先填满关卡。有了正确数量的节点,它将永远是完整的。

我没有用c++做过那么多,所以为了确保它是正确的,我在Java中做了,但是你明白了:

public void insert(Node node) {
    if(root == null) {
        root = node;
        return;
    }
    /* insert using Breadth-first-search (queue to the rescue!) */
    Queue<Node> queue = new LinkedList<Node>();
    queue.offer(root);
    while(true) {
        Node n = queue.remove();
        if(!n.visited) System.out.println(n.data);
        n.visited = true;
        if(n.left == null) {
            n.left = node;
            break;
        } else {
            queue.offer(n.left);
        }           
        if(n.right == null) {
            n.right = node;
            break;
        } else {
            queue.offer(n.right);
        }
    }
}

Javascript实现(为web控制台准备复制粘贴):

ES6实现(带有class关键字的新javascript语法)

  class BinaryTree {
      constructor(value){
          this.root = value;
          this.left = null;
          this.right = null;
      }
      insert(value){
          var queue = [];
          queue.push(this); //push the root
          while(true){
              var node = queue.pop();
              if(node.left === null){
                  node.left = new BinaryTree(value);
                  return;
              } else {
                  queue.unshift(node.left)
              }
              if(node.right === null){
                node.right = new BinaryTree(value);
                return;
              } else {
                queue.unshift(node.right)
              }
          }
      }
  }
  var myBinaryTree = new BinaryTree(5);
  myBinaryTree.insert(4);
  myBinaryTree.insert(3);
  myBinaryTree.insert(2);
  myBinaryTree.insert(1);
     5
   /   
  4     3
 /    (next insertions here)
 2  1    

伪经典模式实现

  var BinaryTree = function(value){
    this.root = value;
    this.left = null;
    this.right = null;
  }
  BinaryTree.prototype.insert = function(value){
    //same logic as before
  }

对您的代码进行一些修改,我希望这对您有所帮助:

Node * Insert(Node * root, int data)
{
  if(root == nullptr)
  {
    Node * NN = new Node();
    root = NN;
    root->data = data;
    root->left = root ->right = NULL;
  }
  else
  {
    if(data < root->data)
    { 
      root->left = Insert(root->left, data);
    }
    else
    {
      root->right = Insert(root->right, data);
    }
  }
  return root;
}

因此,该函数返回更新后的BST的根节点。

我采用了bknopper代码,稍微修改了一下,然后翻译成c++。正如他所说,令人惊讶的是,这并没有很好的记录。

下面是节点结构和插入函数:

struct nodo
{
    nodo(): izd(NULL), der(NULL) {};
    int val;
    struct nodo* izd;
    struct nodo* der;
};
void inserta(struct nodo** raiz, int num)
{
if( !(*raiz) )
{
    *raiz = new struct nodo;
    (*raiz)->val = num;
}
else
{
    std::deque<struct nodo*>  cola;
    cola.push_back(  *raiz  );
    while(true)
    {
        struct nodo *n = cola.front();
        cola.pop_front();
        if( !n->izd ) {
            n->izd = new struct nodo;
            n->izd->val = num;
            break;
        } else {
            cola.push_back(n->izd);
        }
        if( !n->der ) {
            n->der = new struct nodo;
            n->der->val = num;
            break;
        } else {
            cola.push_back(n->der);
        }
    }
  }
}

你可以这样调用它:inserta(&root, val);

root是指向节点结构的指针,val是要插入的整数值。

希望对大家有所帮助。

您应该尝试使用递归方法,例如x = new (x),如果您知道这意味着什么的话。这样,就不用担心根节点了。我将为您编写一些伪代码:

//public function
add(data){
    root = add(data, root)
}
//private helper function 
Node add(data, currentNode){
    if(currentNode = 0)
        return new Node(data)
    if(data less than currentNode's data)
        currentNode.left = add(data, currentNode.left)
    if(data more than currentNode's data)
        currentNode.right = add(data, currentNode.right)
    return currentNode      
}

我做了一个关于在c++中实现BST的教程,在这里