Binary Tree

April 17, 202213 min read

DSA
JavaScript
Tree
What is a Binary Tree

A binary tree is a data structure that consists of nodes arranged in a tree-like structure. Each node has at most two children, referred to as the left child and the right child. The node at the top of the tree is called the root, and the nodes at the bottom of the tree are called leaves.

Binary Tree

Binary trees can be implemented in many different ways, depending on the requirements of the application. One common way to implement a binary tree is to use a class with fields for the data stored at the node and references to the left and right children of the node.

Here is an example implementation of a binary tree class in JavaScript:

class BinaryTreeNode {
  constructor(data) {
    this.data = data
    this.left = null
    this.right = null
  }
}

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

  insert(data) {
    const newNode = new BinaryTreeNode(data)
    if (this.root === null) {
      this.root = newNode
    } else {
      let current = this.root
      while (true) {
        if (data < current.data) {
          if (current.left === null) {
            current.left = newNode
            break
          }
          current = current.left
        } else {
          if (current.right === null) {
            current.right = newNode
            break
          }
          current = current.right
        }
      }
    }
  }

  search(data) {
    let current = this.root
    while (current !== null) {
      if (data === current.data) {
        return true
      }
      if (data < current.data) {
        current = current.left
      } else {
        current = current.right
      }
    }
    return false
  }

  remove(data) {
    this.root = this._remove(this.root, data)
  }

  _remove(node, data) {
    if (node === null) {
      return null
    }
    if (data < node.data) {
      node.left = this._remove(node.left, data)
      return node
    }
    if (data > node.data) {
      node.right = this._remove(node.right, data)
      return node
    }
    if (node.left === null && node.right === null) {
      return null
    }
    if (node.left === null) {
      return node.right
    }
    if (node.right === null) {
      return node.left
    }
    let minNode = this._findMin(node.right)
    node.data = minNode.data
    node.right = this._remove(node.right, minNode.data)
    return node
  }
}

const tree = new BinaryTree()

tree.insert(5)
tree.insert(15)
tree.insert(9)
tree.insert(6)
tree.insert(12)
tree.insert(3)

console.log(tree.search(12)) // BinaryTreeNode { data: 12, left: null, right: null }
console.log(tree.search(6)) // BinaryTreeNode { data: 6, left: null, right: null }
console.log(tree.search(47)) // Not Found

tree.remove(6)
console.log(tree.search(6)) // Not Found

Binary trees have several properties that make them useful for certain types of problems. One property is that the height of a binary tree is logarithmic in the number of nodes it contains. This means that as the number of nodes in the tree increases, the height of the tree grows at a slower rate. This property makes binary trees well-suited for searching and sorting operations, as the time complexity of these operations is often related to the height of the tree.

There are several different types of binary trees, each with its own characteristics. Some common types of binary trees include:

Binary search tree

A binary search tree is a type of binary tree where the value of each node is greater than the values of the nodes in its left subtree and less than the values of the nodes in its right subtree. This property allows for efficient search and insertion operations, as the tree can be traversed in a way that narrows down the possible location of the desired value.

Complete binary tree

A complete binary tree is a type of binary tree where all levels of the tree are fully filled except possibly the last level, and the nodes in the last level are filled from left to right.

Full binary tree

A full binary tree is a type of binary tree where every node has either 0 or 2 children.

Perfect binary tree

A perfect binary tree is a type of binary tree that is both complete and full.

Binary trees are used for a variety of purposes, such as representing hierarchical relationships, searching, sorting, and decision-making. They can be implemented using a variety of techniques, including arrays, linked lists, and dynamic memory allocation.

Conclusion

In conclusion, binary trees are a widely used data structure in computer science, with many practical applications in areas such as file systems, decision-making, web navigation, network routing, and expression parsing. They are implemented using a variety of techniques, including arrays, linked lists, and dynamic memory allocation. Binary trees can be traversed using various techniques, such as inorder, preorder, and postorder traversal, and they can be balanced using techniques such as red-black trees and AVL trees. Overall, binary trees are a powerful tool for organizing and manipulating data in a hierarchical manner.


Vishal Sharma

Hey there! This is Vishal Sharma. I reside and work at Gurgaon, India. I am a Software Engineer and primarily works with JavaScript, ReactJS and NodeJS.
LinkedIn Link

Welcome to my Javascript tech blog! Here, you'll find the latest news and updates in the world of Javascript, as well as tutorials and resources to help you improve your coding skills. From learning the basics of Javascript to advanced concepts like object-oriented programming, I post something for developers of all levels. Whether you're just starting out or you're a seasoned pro, you'll find valuable insights and information on our blog. So stay up-to-date with the latest in Javascript technology by bookmarking this page and checking back often.
Thank you for visiting!