Post/Code

HomeAboutUsesNow

Binary Trees: Part 1

I have been avoiding this. Ever since I first encountered the binary tree in the Daily Coding Problems, I have been procrastinating on this topic. If ever my impostor syndrome regarding my abilities or designation as a 'programmer' had effect it is in situations like this. But, I can't avoid it forever, and you every journey starts with one step, so here we go!

Binary Trees

A binary tree is a data structure that has at most, two children. Since a binary tree can only have at most 2 children, we name them left or right.

Use Cases

  • Typically trees are used to store hierarchical information - ie. files in a computer
  • Manipulate hierarchical data
  • Make information easy to search (tree traversal)
  • Manipulate sorted lists of data
  • Multi-stage decision making
  • Router algorithms

Attributes

  • Moderate access/search (quicker than linked list, slower than arrays)
  • Moderate insertion/deletion (quicker than arrays, slower than unordered linked lists)
  • Trees don’t have an upper limit on number of nodes as nodes are linked using pointers.

Properties

A node on a tree contains the following:

  1. Data
  2. A pointer to the left child
  3. A pointer to the right child

Terms

  • A node with no parent is the root node.
  • A node with no children is called a leaf.

Code

Below is the most basic definition of a node in a binary tree:

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

    // Todo
}

To be continued...

Hat Tip to Geeks for Geeks