Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make binary tree from array in javascript?

I have an array var array = [8,10,12,5,3,6];

Logic

  1. First node would be root node.
  2. If new node value is less or equal =< than parent node, It would be left node of parent node
  3. If new node value is greater > than parent node, It would be right node of parent node

And I am trying to achieve output like below object:

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

Which would be in image like this

enter image description here

I tried below code:

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

Please help me to solve this.

like image 682
Devendra Gokhe Avatar asked Feb 12 '18 10:02

Devendra Gokhe


People also ask

How do you put a binary search tree in an array in a efficient manner?

We have to write the nodes of a binary tree to a file. What is the most space efficient way of writing a binary tree . We can store it in array format with parent in position i and its children in 2i , 2i+1 . But this will waste lot of space in case of sparse binary trees.

How can binary trees be implemented using array explain with the help of an example?

Binary Tree with Array implementation in C++ A binary tree is a special type of tree in which each node of the tree can have at most two child nodes. These child nodes are known as right child and left child. For representing trees, there are two ways, dynamic node representation which uses linked list.


Video Answer


1 Answers

You could use a Node instance for new nodes and a function for inserting nodes.

Then iterate the values and build a new tree.

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; }
like image 53
Nina Scholz Avatar answered Sep 27 '22 18:09

Nina Scholz