JSFiddle - React, Tailwind, and code Playground

by Anjana Silva

TypeScript

class BinarySearchTree {
  private root: TreeNode;
  
  public getRoot(): TreeNode {
      return this.root;
  }
  
  public setRoot(root: TreeNode) {
      this.root = root;
  }
  
  constructor() {
      this.root = null;
  }
  
  public addToTree(value: number): boolean {
    // Create a new node
    const newNode = new TreeNode(value);
    
    // If tree is empty, set new node as root
    if (this.root == null) {
      this.root = newNode;
    } else {
      // Tree is not empty, find the right spot for the new node
      let currentNode = this.root;
      let traversing = true;
      while (traversing) {
        if (currentNode.value == newNode.value) {
          // Duplicates are not accepted
          traversing = false;
          return false;
        } else if (newNode.value < currentNode.value) {
          // Traverse left of the node
          if (currentNode.left == null) {
              currentNode.left = newNode;
              traversing = false;
              return true;
          } else {
              // Traversing left of the current node
              currentNode = currentNode.left;
          }
        } else if (newNode.value > currentNode.value) {
            // Traverse right of the node
            if (currentNode.right == null) {
                currentNode.right = newNode;
                traversing = false;
                return true;
            } else {
                // Traversing right of the current node
                currentNode = currentNode.right;
            }
        }        
      }
    }
  }
  
  public breadthFirstSearch() : number[] {
      // Create a queue to keep track of nodes that needs to be visited
      let toBeVisitedQueue = new Array<TreeNode>();
      // Create an array to keep track of visited node values
      let visitedArray = new Array<number>();
      
      // Start traversing from the root
      toBeVisitedQueue.push(this.root);
      
      // While the queue is not empty
      while...