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:
- You have a Grandparent (The Root).
- They have Children (Branches).
- The children have their own children.
- People without children are called Leaves.
- 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
- Full Binary Tree: Every node has 0 or 2 children.
- Complete Binary Tree: All levels are filled except possibly the last, and the last level is filled from left to right.
- Perfect Binary Tree: All internal nodes have two children and all leaves are at the same level.
- 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?"