javascript - 插入二叉树的第一个元素,是放在左边还是右边?

标签 javascript algorithm data-structures binary-tree

所以我尝试在 JavaScript 中创建一个二叉树

function ToBinaryTree ( arr )
{
    // creates a binary tree from an array arr of comparable objects

    this.Tree = { left: undefined, right: undefined };

    this.CreateNode = function ( value )
    {
          return { val : undefined, left : undefined, right : undefined }
    };
    this.Insert = function (elem)
    {
          var node = this.CreateNode(elem); 
        if ( this.Tree.left == undefined ) 
        // ... ??
    };

    // insert elements from array provided in "constructor"
    arr.forEach(function(x){
        this.Insert(x); 
    }.bind(this));

    this.Contains = function (elem)
    {
         // ...
    };

    return this;
}

我不知道第一个插入的元素应该放在右边还是左边,如果是,比如说,左边 (this.Tree.left),然后我是否通过检查 this.Tree.left == undefined 来检查是否没有插入元素???

最佳答案

第一个元素在根上:

this.CreateNode = function (value) {
  return { 
    val: value,      // Store the root value here instead of undefined
    left: undefined, 
    right: undefined 
  };
};

附注刚刚意识到这个错误不是唯一的问题,你还有一个“树”构造函数(?)...不要试图将节点与整个树区分开来,在大多数情况下,假设树是更简单的与其根节点相同,并有一个额外的“外部”静态插入方法,可以处理“空”或未定义的树参数(根据需要返回新树)

p.p.s.如果您使用 undefined 作为空树标记,您可以直接覆盖插入时的值。

关于javascript - 插入二叉树的第一个元素,是放在左边还是右边?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36704118/

相关文章:

javascript - 如果输入的字符串匹配,它会显示带有 javascript 的 HTML 元素

algorithm - 两个数组中元素的和相同

c++ - 线程安全的简单 C++ 容器类

arrays - 返回最大和的子数组

data-structures - Stack with PushAt/PopAt 还是 Stack 吗?

c++ - 添加到哈希表

javascript - 调用函数作为 Enzyme 中的 prop 传递

javascript - angularJS $http.get 与 API 通信

javascript - 使用 jquery 转换页面加载时的超链接

arrays - 求解最大积子数组的正确方法