How to convert an array to a binary tree with javascript?

by lindsey.homenick , in category: Javascript , a year ago

How to convert an array to a binary tree with javascript?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by rollin , a year ago

@lindsey.homenick 

To convert an array to a binary tree using JavaScript, you can follow these steps:

  1. Define a class Node with properties for value, left, and right.
  2. Create a constructBinaryTree function that takes in an array as a parameter.
  3. Initialize an empty root variable.
  4. Use a loop to iterate through every element in the array.
  5. Inside the loop, create a new Node with the current element as the value.
  6. Check if the root is empty. If it is, set the current Node as the root.
  7. If the root is not empty, insert the current Node into the tree. Create a traverse function that takes in a node parameter (initially set to the root) and the current Node. Inside the traverse function, check if the node has a left child. If it does not, insert the current Node as the left child. If it does have a left child, recursively call the traverse function with the left child as the new node. Inside the traverse function, check if the node has a right child. If it does not, insert the current Node as the right child. If it does have a right child, recursively call the traverse function with the right child as the new node.
  8. Return the root as the final binary tree.


Here's an example implementation:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
class Node {
  constructor(value) {
    this.value = value;
    this.left = null;
    this.right = null;
  }
}

function constructBinaryTree(arr) {
  let root = null;

  for (let i = 0; i < arr.length; i++) {
    const newNode = new Node(arr[i]);

    if (!root) {
      root = newNode;
    } else {
      traverse(root, newNode);
    }
  }

  return root;
}

function traverse(node, newNode) {
  if (!node.left) {
    node.left = newNode;
  } else if (!node.right) {
    node.right = newNode;
  } else {
    // randomly choose to go left or right
    const direction = Math.random() < 0.5 ? "left" : "right";
    traverse(node[direction], newNode);
  }
}

// Example usage:
const array = [1, 2, 3, 4, 5];
const binaryTree = constructBinaryTree(array);
console.log(binaryTree);

// Output:
// Node {
//   value: 1,
//   left: Node { value: 2, left: Node {...}, right: Node {...} },
//   right: Node { value: 3, left: Node {...}, right: Node {...} }
// }


Note that in this example, we randomly choose whether to go left or right when inserting a node when both children are already present. This results in a random binary tree structure.