binary tree in javascript

Here's an example implementation of a binary tree in JavaScript using classes:

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

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

  insert(value) {
    const node = new Node(value);

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

    let current = this.root;

    while (true) {
      if (value < current.value) {
        if (!current.left) {
          current.left = node;
          break;
        }

        current = current.left;
      } else {
        if (!current.right) {
          current.right = node;
          break;
        }

        current = current.right;
      }
    }
  }

  DFSInOrder(callback) {
    function traverse(node) {
      if (node.left) traverse(node.left);
      callback(node);
      if (node.right) traverse(node.right);
    }

    traverse(this.root);
  }

  DFSPreOrder(callback) {
    function traverse(node) {
      callback(node);
      if (node.left) traverse(node.left);
      if (node.right) traverse(node.right);
    }

    traverse(this.root);
  }

  DFSPostOrder(callback) {
    function traverse(node) {
      if (node.left) traverse(node.left);
      if (node.right) traverse(node.right);
      callback(node);
    }

    traverse(this.root);
  }

  BFS(callback) {
    const queue = [this.root];
    let node = null;

    while (queue.length) {
      node = queue.shift();
      callback(node);

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

// Example usage
const tree = new BinaryTree();

tree.insert(10);
tree.insert(6);
tree.insert(15);
tree.insert(3);
tree.insert(8);
tree.insert(20);

tree.DFSInOrder((node) => {
  console.log(node.value);
});
1720 chars
100 lines

This implementation includes methods for inserting nodes, and for performing depth-first and breadth-first searches on the tree (in-order, pre-order, post-order, and level-order). Note that the DFSInOrder method prints the nodes' values in ascending order by default.

gistlibby LogSnag