【问题标题】:Binary search tree add method not sorting every input - JavaScript二叉搜索树添加方法不对每个输入进行排序 - JavaScript
【发布时间】:2018-09-22 16:36:22
【问题描述】:

我正在研究二叉搜索树,在向树中添加值时遇到问题。 当我按顺序(降序或升序)添加值(数字)时,它们被添加到正确的位置,但是如果我添加的值应该位于树中已经存在的值之间的某个位置,它们不会被排序。可以看到图中,数字[3]加在1之后,但是应该在[4]和[1]之间 所以问题是,我到底做错了什么以及如何解决它

我正在为图片下方的添加功能添加我的代码

节点对象

function Node(data){
this.data=data;
this.left=null;
this.right=null;}

function BinarySearchTree(){
this.root = null;
var current=null;
var newNode=null;

this.add = function(data){
    var root = this.root;
        if(!root){
            this.root= new Node(data);
            return;
        }else{
            if(this.ifExists(data)){
            }else{
                current=root;
                newNode= new Node(data);

                while(current){
                    if(data<current.data){
                        if(!current.left){
                                current.left=newNode;
                            break;
                        }else{
                                current= current.left;
                             }
                    }else{
                        if(!current.right){
                                current.right=newNode;
                            break;
                        }else{
                                current=current.right;
                            }
                        }
                    }
                }
            }
        }
}
this.ifExists=function(data){
         var current = this.root;
//       console.log(current);
         while(current){
             if(data==current.data){
                 return true;
             }
             current = data < current.value ? current.left : current.right;
         }
         return false;
     }
}

如何调用 add 函数

var bst= new BinarySearchTree();
bst.add(7);
bst.add(8);
bst.add(4);
bst.add(1);
bst.add(15);
bst.add(67);
bst.add(9);
bst.add(3);
console.log(bst);

console.log(bst)的输出;

【问题讨论】:

  • 你有一些else else 部分,之前没有if
  • @NinaScholz 错误地将代码复制到 stackoverflow 中,只是修复了代码。但这不是问题
  • 我不明白这个问题。您将 3 标记为错误的位置,但 1 应该是左孩子,因为它小于 4。3 应该是右孩子。
  • 您应该添加mvce,以便清楚问题出在哪里。如果我添加缺少的代码以使其运行,它可以正常工作。我得到了一个有效的 bst。
  • 请添加缺少的部分,例如ifExists

标签: javascript sorting binary-search-tree


【解决方案1】:

3 应该在右侧,因为它比1 大。在您的输出中,这是真的。在您的图片中,您在那里犯了一个错误。

除此之外,你的树还不错。 1 小于 3 的事实是正确的,但 BST 仅保证有序树遍历产生树数据的排序列表,而不是树中每个较小的值都低于较大的值。如果您执行有序树遍历,您的 BST 会给您1, 3, 4, 7, 8, 15

如果您不知道如何按顺序进行树遍历,请查看以下内容: 来自Wikipedia

当节点底部的点被触摸时,只需记下每个数据。

【讨论】:

    猜你喜欢
    • 2011-12-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-11-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多