简体   繁体   English

在 JavaScript 中用于在二叉树中插入节点的递归函数中的错误

[英]Error in Recursive Function Used For Inserting a Node in a Binary Tree in JavaScript

I am getting undefined after the node is inserted in the tree, don't know why is that happening.将节点插入树中后,我变得未定义,不知道为什么会发生这种情况。 Here's what is happening - after the node is inserted, the function should return true, but it instead returns undefined.这是发生的事情 - 在插入节点后,该函数应该返回 true,但它返回 undefined。 After inserting the node, the code doesn't stop and goes back to if check condition, sets 'current' to '7', this keeps happening until 'current' is '10'(root value) and then it finally goes back to insert() function which returns undefined.插入节点后,代码不会停止并返回到 if 检查条件,将 'current' 设置为 '7',这种情况一直发生,直到 'current' 为 '10'(根值),然后它最终返回insert() 函数返回未定义。 My only problem is that why is it returning undefined, and why is it going back to root after inserting the node in the desired place.我唯一的问题是为什么它返回未定义,以及为什么在将节点插入所需位置后返回到 root。 Can someone please tell me?有人可以告诉我吗? Am I missing something very small?我错过了一些非常小的东西吗?

by the way, the value I inserted is 8. tree.insert(8);顺便说一下,我插入的值是 8。 tree.insert(8);

class Node{
    constructor(val){
        this.val = val;
        this.left = null;
        this.right = null;
    }
}

class BinarySearchTree{
    constructor(){
        this.root = null;
    }

    insert(val){
        if(!this.root){
          this.root = newNode;
          return this;
        }
        let newNode = new Node(val);
        if(val === this.root.val)return false;
     
        function recursiveInsert(current,newNode){ 
            if(newNode.val === current.val)return false;      

            if(newNode.val > current.val){
              if(!current.right){
                  current.right = newNode;             
                  return true;
              }           
              recursiveInsert(current.right,newNode);
            }

            if(newNode.val<current.val){   
              if(!current.left){
                  current.left = newNode;              
                  return true;
            }
            recursiveInsert(current.left, newNode);
          }        
       }    
      return recursiveInsert(this.root,newNode);                         
    }
  }

let tree = new BinarySearchTree();

tree.root = new Node(10);
tree.root.left = new Node(7);
tree.root.right = new Node(15);
tree.root.left.right = new Node(9);

There are these issues:有这些问题:

  • In the if(!this.root){ block, you reference newNode before it has received a value, so move the initialisation of newNode before this if statement.if(!this.root){块中,您在newNode收到值之前引用它,因此将newNode的初始化移动到此if语句之前

  • In the same block you return this , but you write that you want to return a boolean, so change that to return true;在同一个块中,您return this ,但您写下要返回一个布尔值,因此将其更改为return true;

  • The recursive calls should be used to return whatever that call returned, so prefix them with return , just like you have done in the last line where you made that initial call.递归调用应该用于返回该调用返回的任何内容,因此在它们前面加上return ,就像您在进行初始调用的最后一行中所做的那样。

Demo演示

I would also suggest building the initial tree with the insert method.我还建议使用insert方法构建初始树。 And add an iterator so you can have a quick output of your tree in inorder sequence.并添加一个迭代器,以便您可以按中序快速输出树。

Note that there is an else if condition that is always true, so just use else :请注意,有一个else if条件始终为真,因此只需使用else

 class Node { constructor(val) { this.val = val; this.left = null; this.right = null; } // Add this method for inorder traversal of the values * inorder() { if (this.left) yield * this.left.inorder(); yield this.val; if (this.right) yield * this.right.inorder(); } } class BinarySearchTree { constructor() { this.root = null; } insert(val) { let newNode = new Node(val); // First create the node if (!this.root) { this.root = newNode; return true; // you wanted a boolean } // This is not necessary: it already happens in the function below // if(val === this.root.val)return false; function recursiveInsert(current,newNode) { if (newNode.val === current.val) return false; if (newNode.val > current.val) { if (!current.right) { current.right = newNode; return true; } // Return the result return recursiveInsert(current.right, newNode); } else { // it is the only possibility left if (!current.left) { current.left = newNode; return true; } // Return the result return recursiveInsert(current.left, newNode); } } return recursiveInsert(this.root, newNode); } } let tree = new BinarySearchTree(); // Build the tree only with the insert-method tree.insert(10); tree.insert(7); tree.insert(15); tree.insert(9); tree.insert(8); // Add the value you wanted to test with tree.insert(15); // Try some duplicate console.log(...tree.root.inorder());

You can make the code still a bit nicer by making the recursive insert function a method of the Node class.您可以通过将递归插入函数作为Node类的方法来使代码更好看。 Also, enrich the BinarySearchTree constructor, so that it can get a number of values to start with, much like the native Array constructor works.此外,丰富BinarySearchTree构造函数,以便它可以从多个值开始,就像本机Array构造函数一样。

 class Node { constructor(val) { this.val = val; this.left = null; this.right = null; } * inorder() { if (this.left) yield * this.left.inorder(); yield this.val; if (this.right) yield * this.right.inorder(); } insert(val) { if (val === this.val) return false; if (val > this.val) { if (this.right) return this.right.insert(val); this.right = new Node(val); } else { if (this.left) return this.left.insert(val); this.left = new Node(val); } return true; } } class BinarySearchTree { constructor(...values) { this.root = null; for (let val of values) this.insert(val); } * inorder() { if (this.root) yield * this.root.inorder(); } insert(val) { if (this.root) return this.root.insert(val); this.root = new Node(val); return true; } } let tree = new BinarySearchTree(10, 7, 15, 9); tree.insert(8); tree.insert(15); console.log(...tree.inorder());

You should return the recursiveCall or you will get undefined because the recursive call take time to execute and the function won't wait for it to return something.你应该返回 recursiveCall 否则你会得到 undefined 因为递归调用需要时间来执行并且函数不会等待它返回一些东西。

// ...code
return recursiveInsert(current.right,newNode);
// and
return recursiveInsert(current.left,newNode);

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

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