🌇DSA
← Back
Data StructureIntermediate
🌲

Binary Trees

Hierarchical node-based structure

⏱️ 6–8 hours🧩 10 LeetCode
🔒 Login to unlock solutions and track progress. Login

What is it?

A binary tree is like a family tree. Every person (node) can have at most two children — a left child and a right child. The very top is called the root.

In a Binary Search Tree (BST): left children are smaller, right children are larger. This makes search very fast — O(log n).

Common Traversals

  • Inorder (Left → Node → Right) — prints values in sorted order for a BST
  • Preorder (Node → Left → Right) — useful for copying or serialising a tree
  • Postorder (Left → Right → Node) — useful for deleting a tree safely
  • Level Order (BFS) — visits all nodes layer by layer

Real-World Examples

File system folders
Company org chart
Compiler expression tree
ML decision tree
HTML / DOM tree
Chess game move tree

Code Example

What this code shows

Build a BST: root = 4, left subtree holds 1, 2, 3 and right child is 6. Inorder traversal visits left → node → right at every step, which naturally prints the values in ascending order.

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

// inorder: LEFT first, then NODE, then RIGHT
function inorder(node) {
if (!node) return;     // base case: empty node
inorder(node.left);    // step 1 — go left
console.log(node.val); // step 2 — visit this node
inorder(node.right);   // step 3 — go right
}

// build the BST
const root    = new Node(4);
root.left     = new Node(2);  root.right     = new Node(6);
root.left.left = new Node(1); root.left.right = new Node(3);

inorder(root); // prints: 1  2  3  4  6

Expected Output

1
2
3
4
6

LeetCode Practice