create a binary tree in javascript

To create a binary tree in JavaScript, we can define a class for the nodes of the tree and define the methods for traversing the tree. Here's an example:

index.tsx
class Node {
  constructor(value) {
    this.value = value;
    this.left = null;
    this.right = null;
  }
}

class BinaryTree {
  constructor() {
    this.root = null;
  }

  addNode(value) {
    let newNode = new Node(value);

    if (!this.root) {
      this.root = newNode;
      return;
    }

    let current = this.root;
    while (true) {
      if (value < current.value) {
        if (!current.left) {
          current.left = newNode;
          return;
        }
        current = current.left;
      } else {
        if (!current.right) {
          current.right = newNode;
          return;
        }
        current = current.right;
      }
    }
  }

  // Depth-First Traversal

  // In-order traversal
  traverseInOrder(node = this.root) {
    if (node) {
      this.traverseInOrder(node.left);
      console.log(node.value);
      this.traverseInOrder(node.right);
    }
  }

  // Pre-order traversal
  traversePreOrder(node = this.root) {
    if (node) {
      console.log(node.value);
      this.traversePreOrder(node.left);
      this.traversePreOrder(node.right);
    }
  }

  // Post-order traversal
  traversePostOrder(node = this.root) {
    if (node) {
      this.traversePostOrder(node.left);
      this.traversePostOrder(node.right);
      console.log(node.value);
    }
  }

  // Breadth-First Traversal
  traverseBreadthFirst() {
    let queue = [];
    let result = [];

    if (this.root) {
      queue.push(this.root);

      while (queue.length > 0) {
        let node = queue.shift();
        result.push(node.value);

        if (node.left) {
          queue.push(node.left);
        }

        if (node.right) {
          queue.push(node.right);
        }
      }
    }

    console.log(result);
  }
}

// Example usage
let myTree = new BinaryTree();
myTree.addNode(4);
myTree.addNode(2);
myTree.addNode(6);
myTree.addNode(1);
myTree.addNode(3);
myTree.addNode(5);
myTree.addNode(7);

myTree.traverseInOrder(); // 1 2 3 4 5 6 7
myTree.traversePreOrder(); // 4 2 1 3 6 5 7
myTree.traversePostOrder(); // 1 3 2 5 7 6 4
myTree.traverseBreadthFirst(); // 4 2 6 1 3 5 7
2102 chars
109 lines

In this implementation, we defined a class for the nodes of the binary tree and a class for the binary tree itself. We provided a method for adding new nodes to the binary tree, and methods for performing depth-first and breadth-first traversals of the tree. The depth-first traversal methods use recursion to traverse the tree, while the breadth-first traversal method uses a queue to traverse the tree.

gistlibby LogSnag