如何在javascript中从数组生成二叉树?

时间:2018-02-12 10:16:48

标签: javascript arrays tree binary-tree

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

逻辑

  1. 第一个节点是根节点。
  2. 如果新节点值小于或等于=<父节点,则它将是父节点的左侧节点
  3. 如果新节点值比父节点大>,那么它将是父节点的正确节点
  4. 我正在努力实现如下对象的输出:

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

    这将是像这样的图像

    enter image description here

    我尝试了以下代码:

    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);
    

    请帮我解决这个问题。

4 个答案:

答案 0 :(得分:3)

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

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

&#13;
&#13;
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);
&#13;
.as-console-wrapper { max-height: 100% !important; top: 0; }
&#13;
&#13;
&#13;

答案 1 :(得分:0)

通过递归方法

尝试这样的事情

&#13;
&#13;
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);
&#13;
&#13;
&#13;

答案 2 :(得分:0)

虽然它接近尼娜的回答,但我相信会更简洁一点;

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 :(得分:0)

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()