Binary Tree and Binary Search Tree

By Published 5 min read

Binary Tree and Binary Search Tree

Introduction:

Arrays, linked lists, stacks and queues are all linear: each item has at most one item before it and one after it. Many real things are not linear. A company has a CEO with managers under them and employees under each manager. A folder contains files and other folders. A web page is a tree of HTML elements (the DOM). To model these, we use a tree.

In this lesson we will learn the vocabulary of trees, then focus on the most important kind: the binary tree, and its sorted version, the binary search tree (BST).

Tree Terminology

            8          <- root
          /   \
         3     10      <- 3 and 10 are children of 8
        / \      \
       1   6      14   <- 1, 6 and 14 have no children: leaves
  • Node: an element of the tree that holds a value.
  • Root: the top node, which has no parent (8 above).
  • Parent and child: a node directly above another is its parent; the node below is its child.
  • Leaf: a node with no children (1, 6 and 14).
  • Edge: the link between a parent and a child.
  • Height: the number of edges on the longest path from the root to a leaf (2 above).
  • Subtree: a node together with all of its descendants.

What Is a Binary Tree?

A binary tree is a tree in which every node has at most two children, called the left child and the right child.

Some special shapes are worth knowing:

  • Full binary tree: every node has either 0 or 2 children.
  • Complete binary tree: every level is filled except possibly the last, which is filled from left to right. Heaps are complete binary trees.
  • Balanced binary tree: the heights of the left and right subtrees of every node differ by at most one, which keeps the tree short.

What Is a Binary Search Tree?

A binary search tree is a binary tree with one extra rule, which applies to every node:

  • All values in its left subtree are smaller than the node.
  • All values in its right subtree are larger than the node.

The tree in the diagram above is a BST. Because of this rule, searching works like the binary search you learned in the Searching Algorithms lesson: at each node you go left or right and ignore the other half of the tree.

Building a BST in JavaScript

1. The Node:

class TreeNode {
  constructor(value) {
    this.value = value;
    this.left = null;
    this.right = null;
  }
}
class BinarySearchTree {
  constructor() {
    this.root = null;
  }

  insert(value) {
    const node = new TreeNode(value);
    if (!this.root) {
      this.root = node;
      return;
    }

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

  contains(value) {
    let current = this.root;
    while (current) {
      if (value === current.value) return true;
      current = value < current.value ? current.left : current.right;
    }
    return false;
  }

  min() {
    let current = this.root;
    while (current && current.left) current = current.left;
    return current ? current.value : null;
  }

  max() {
    let current = this.root;
    while (current && current.right) current = current.right;
    return current ? current.value : null;
  }
}

3. Using It:

const bst = new BinarySearchTree();
[8, 3, 10, 1, 6, 14].forEach((n) => bst.insert(n));

console.log(bst.contains(6));  // true
console.log(bst.contains(7));  // false
console.log(bst.min());        // 1
console.log(bst.max());        // 14

The smallest value is always the leftmost node, and the largest is always the rightmost node.

Tree Traversals

Traversing a tree means visiting every node once. Because a tree is not a straight line, there are several possible orders. The first three are depth-first and are easiest to write with recursion.

1. In-order (left, node, right):

function inOrder(node, result = []) {
  if (!node) return result;
  inOrder(node.left, result);
  result.push(node.value);
  inOrder(node.right, result);
  return result;
}

console.log(inOrder(bst.root)); // [1, 3, 6, 8, 10, 14]

For a BST, in-order traversal always returns the values in sorted order. That is a handy way to check whether a tree is a valid BST.

2. Pre-order (node, left, right):

function preOrder(node, result = []) {
  if (!node) return result;
  result.push(node.value);
  preOrder(node.left, result);
  preOrder(node.right, result);
  return result;
}

console.log(preOrder(bst.root)); // [8, 3, 1, 6, 10, 14]

Pre-order visits a parent before its children, so it is used to copy or serialize a tree.

3. Post-order (left, right, node):

function postOrder(node, result = []) {
  if (!node) return result;
  postOrder(node.left, result);
  postOrder(node.right, result);
  result.push(node.value);
  return result;
}

console.log(postOrder(bst.root)); // [1, 6, 3, 14, 10, 8]

Post-order visits children before their parent, so it is used to delete a tree or calculate folder sizes (you need the size of each subfolder first).

4. Level-order (breadth-first):

Level-order visits the tree one level at a time, from top to bottom. It uses the queue from the previous lesson:

function levelOrder(root) {
  if (!root) return [];
  const result = [];
  const queue = [root];

  while (queue.length) {
    const node = queue.shift();
    result.push(node.value);
    if (node.left) queue.push(node.left);
    if (node.right) queue.push(node.right);
  }

  return result;
}

console.log(levelOrder(bst.root)); // [8, 3, 10, 1, 6, 14]

Time Complexity

  • Search, insert, delete in a balanced BST: O(log n), because each step halves the remaining tree.
  • Search, insert, delete in an unbalanced BST: O(n) in the worst case.
  • Any traversal: O(n), because every node is visited once.

Why can a BST become unbalanced? If you insert values that are already sorted, such as 1, 2, 3, 4, 5, every new node goes to the right and the tree turns into a long chain that behaves like a linked list. Self-balancing trees such as AVL trees and Red-Black trees fix this by rotating nodes after each insert or delete, so the height stays around log n. Many language libraries and databases use them internally.

Real-World Uses of Trees

  • The DOM: every web page is a tree of elements, and React’s virtual DOM is a tree too.
  • File systems: folders and files.
  • Database indexes: B-trees and B+ trees (a generalisation of BSTs with many children per node) let databases like MySQL find rows quickly.
  • Autocomplete: a tree called a trie stores words letter by letter.
  • Heaps and priority queues: a heap is a complete binary tree.
  • Compilers: source code is parsed into an abstract syntax tree (AST).

Conclusion:

Trees model data with a hierarchy, and binary search trees keep that data sorted so you can search, insert and delete in O(log n) time when the tree is balanced. You learned tree terminology, the binary tree and BST rules, built a BST in JavaScript, and wrote the four traversals: in-order, pre-order, post-order and level-order. Next, the Heap Sort lesson shows a special binary tree in action, and the Graph lesson generalises trees to networks where any node can connect to any other.

Khan Waseem is a tech lead and full-stack engineer in Bengaluru, building hospitality and SaaS software with Node.js, React and React Native. See the resume