【问题标题】:How to make binary tree from array in javascript?如何在javascript中从数组制作二叉树?
【发布时间】:2018-02-12 10:16:47
【问题描述】:

我有一个数组var array = [8,10,12,5,3,6];

逻辑

  1. 第一个节点是根节点。
  2. 如果新节点值小于或等于=<父节点,则为父节点的左节点
  3. 如果新节点值>大于父节点,则为父节点的右节点

我正在尝试实现如下对象的输出:

{
   value:8,
   left:{
      value:5,
      left:{ value:3 },
      right:{value:6}
   },
   right:{
      value:10,
      right:{value:12}
   }
}

这会是这样的图像

我试过下面的代码:

var arr = [8,10,12,5,3,6];
var root = arr[0];
var rv = {};
for (var i = 0; i < arr.length; i++){
    if(arr[i] < root){
    rv.left = arr[i];
  }else{
    rv.right = arr[i];
  }
}
console.log(rv);

请帮我解决这个问题。

【问题讨论】:

  • 你试过的代码的输出是什么?

标签: javascript arrays tree binary-tree


【解决方案1】:

您可以为新节点使用Node 实例,并为插入节点使用函数。

然后迭代这些值并构建一棵新树。

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

function insertNode(tree, value) {
    var node = tree,
        key;
    while (node.value !== value) {
         key = value < node.value ? 'left' : 'right';
         if (!node[key]) {
             node[key] = new Node(value);
             break;
         }
         node = node[key];
    }
    return tree;
}

var array = [8, 10, 12, 5, 3, 6],
    tree = array.reduce((t, v) => t ? insertNode(t, v) : new Node(v), null);

console.log(tree);
.as-console-wrapper { max-height: 100% !important; top: 0; }

【讨论】:

  • 你没有提到如何为这棵树序列化数组。是按顺序、后序、预序还是完全任意?
  • @Rick,有必要吗?
  • 在代码中,你也可以从树中将它转换回原始数组吗?否则,看起来树和数组之间没有逻辑关系。
【解决方案2】:

虽然接近 Nina 的回答,但我认为它更简洁一些;

var data = [8,10,12,5,3,6],
    tree;

function insertBinTree (t = {value: void 0, left: void 0, right: void 0}, n){
  t.value !== void 0 ? t.value > n ? t.left = insertBinTree(t.left,n)
                                   : t.right = insertBinTree(t.right,n)
                     : t.value = n;
  return t;
}

tree = data.reduce(insertBinTree, void 0);
console.log(tree);
.as-console-wrapper {
max-height: 100% !important
}

【讨论】:

    【解决方案3】:

    通过递归方法尝试这样的事情

    var binary = {};
    var arr = [8,5,10,3,6,12];
    
    function makeBinary(binary,number){
      if(binary.value === undefined){
        binary.value = number;
      }else if(number > binary.value){
        if(binary.right === undefined){
          binary.right = {value:number};  
        }else{
          binary.right = makeBinary(binary.right,number);
        }
      }else{
        if(binary.left === undefined){
          binary.left = {value:number};  
        }else{
          binary.left = makeBinary(binary.left,number);
        }
      }
      return binary;
    }
    
    for(let i in arr){
      makeBinary(binary,arr[i]);
    }
    
    console.log(binary);

    【讨论】:

      【解决方案4】:

      class Node {
          constructor(val){
              this.val=val;
              this.right=null;
              this.left=null;
          }
      }
      
      
      class Bst{
          constructor(){
              this.root=null;
          }
      
          insert(val){
              let newNode= new Node (val)
              if (!this.root) this.root=newNode;
          let current =this.root;        
              while (true) {
                  if(val === current.val) return undefined;
                  if(current.val<val){
                      if (current.right===null){
                          current.right=newNode;
                          return this
                      }
                          else
                          current=current.right}
                  if(current.val>val){
                      if (current.left===null){
                          current.left=newNode;
                          return this
                      }
                          else
                          current=current.left}
                      
              }
              
          
          }
          print (){
              let all="Root=";
          let visit=(current=this.root)=>{
              if(!current.left && !current.right){
                  if(all[all.length-1]<current.val)
                       all+=`,LeR${current.val}`
                       else
                       all+=`,LeL${current.val}`
                      }
      else{
          if(all[all.length-1]<current.val)
               all+=`,FR${current.val}`
               else
                        all+=`,FL${current.val}`
                  }
             
         if (current.left) visit(current.left)
         if (current.right)  visit(current.right)
              }
              visit()
              all+=` ,valid bst:${this.isValidBST()}`
              return all
      
          }
      
       isValidBST(node=this.root, min = null, max = null) {
      if (!node) return true;
      if (max !== null && node.data >= max) {
        return false;
      }
      if (min !== null && node.data <= min) {
        return false;
      }
      const leftSide = this.isValidBST(node.left, min, node.data);
      const rightSide = this.isValidBST(node.right, node.val, max);
      
      return leftSide && rightSide;
          }
      
      find(val){
          let found=false
          let innerFind=(current=this.root)=>{
          if (val>current.val) 
             if (current.right != null) return innerFind(current.right)
              if(val===current.val)
              found= true 
         else
            if (current.left != null)return innerFind(current.left)
              if(val===current.val)
                  found= true 
          return found
              }
              return innerFind()
          }
      
      }
      
      
      
      
      let tree=new Bst
      
      tree.insert(8)
      tree.insert(10)
      tree.insert(13)
      tree.insert(3)
      tree.insert(1)
      tree.insert(6)
      tree.insert(4)
      tree.insert(7)
      tree.insert(2)
      tree.print()

      【讨论】:

      • 您好,欢迎来到 stackoverflow,感谢您的回答。虽然这段代码可能会回答这个问题,但您是否可以考虑添加一些解释来说明您解决了什么问题,以及您是如何解决的?这将有助于未来的读者更好地理解您的答案并从中学习。
      • 这实现了一个 BST,其功能包括 Insert print all 并检查 BST 是否有效,并且 find(布尔值,但可以轻松更改)只需复制并粘贴到控制台即可查看它是如何工作的。
      【解决方案5】:

      您可以通过称为递归的技术来做到这一点。 用结构(left_subtree,key,right_subtree)制作一个数组 在你的情况下 var 数组 = [[3,5,6],8,[null,10,12]

      class TreeNode {
          constructor(key) {
              this.key = key;
              this.right = null;
              this.left = null;
          }
      }
      
      function parseTuple(data) {
          if (data === null) {
              let node = null;
              return node;
          }
          else if (data.length === 3) {
              let node = new TreeNode(data[1]);
              node.left = parseTuple(data[0]);
              node.right = parseTuple(data[2]);
              return node;
          }
          else {
              let node = new TreeNode(data);
              return node;
          }
      
      }

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-11-07
        • 2023-03-28
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多