Core Module
12 min forge

Trees Basics

Master the hierarchical data structure that rules the tech world. Learn about nodes, edges, and the vocabulary of trees.

🌳 Tree Basics: Hierarchical mastery

A Tree is a non-linear data structure representing a hierarchy. Unlike arrays or linked lists, each element (Node) can have multiple "children."

πŸ’‘ The Logic (ELI5)

Think of a Family Tree:

  1. You have a Grandparent (The Root).
  2. They have Children (Branches).
  3. The children have their own children.
  4. People without children are called Leaves.
  5. Everyone except the Grandparent has exactly one Parent.

πŸ” The Deep Dive

Core Vocabulary

  • Root: The top-most node (only one per tree).
  • Edge: The link between two nodes.
  • Leaf: A node with zero children.
  • Height: The longest path from a node to a leaf.
  • Depth: The distance from the root to a specific node.

Binary Trees

The most common type of tree in interviews. In a Binary Tree, every node has at most 2 children (Left and Right).


πŸ› οΈ Code Forge: Binary Tree Node

javascript Standard
/** * Binary Tree Node structure */ class TreeNode { constructor(value) { this.value = value; this.left = null; this.right = null; } } // Creating a simple tree // 1 // / \ // 2 3 const root = new TreeNode(1); root.left = new TreeNode(2); root.right = new TreeNode(3);

🎯 Interview Pulse

Tree Types you MUST know

  1. Full Binary Tree: Every node has 0 or 2 children.
  2. Complete Binary Tree: All levels are filled except possibly the last, and the last level is filled from left to right.
  3. Perfect Binary Tree: All internal nodes have two children and all leaves are at the same level.
  4. Balanced Tree: The height difference between left and right subtrees is minimal (usually $\le 1$).

Top Tip

Trees are almost always solved using Recursion. If you're stuck on a tree problem, ask yourself: "If I knew the answer for my left child and my right child, could I solve the problem for myself?"