Data Structures & Algorithms: Industry Edition

Unit 4: Trees

Binary Trees, BST, Traversals, LCA & Kth Element โ€” with real examples from Nykaa, Linux File System & MongoDB.

๐Ÿข Real Projects  |  ๐Ÿ’ป 5 Lab Programs (Python + C)  |  ๐Ÿ“ 25 MCQs  |  ๐ŸŽฏ 3 Interview Questions

Section 1

Industry Hook โ€” The Real-World Problem First

๐Ÿ’„ The Nykaa Problem: 5 Million Products in a Hierarchy

Nykaa, India's largest beauty e-commerce platform, has over 5 million products organized into a deep category hierarchy:

                   Nykaa
              /     |      \
         Beauty   Fashion   Wellness
         /    \       |
   Skincare  Makeup  Ethnic
    /    \
Moisturizer Sunscreen
   /   \
Under โ‚น500  Premium

When a customer searches "moisturizers under โ‚น500," the system must navigate this tree to reach the correct category โ€” that's tree traversal. When an admin adds a new sub-category, they insert a node โ€” that's tree insertion. When Nykaa needs to find the common category between "Sunscreen" and "Moisturizer," it finds "Skincare" โ€” that's the Lowest Common Ancestor (LCA).

The same tree structure powers your computer's file system (C:\ โ†’ Users โ†’ Documents), the Linux kernel's VFS, every database index (MongoDB uses B-Trees), and DOM manipulation in every web browser.

This is exactly the problem trees solve. Let's understand how.

๐Ÿ‡ฎ๐Ÿ‡ณ NykaaLinuxMongoDBChrome DOM
Section 2

Concept Explanation โ€” Theory, Earned

2.1 Binary Trees

Layer 1 โ€” Intuition

A tree is like a family tree โ€” one ancestor (root) at the top, and each person has at most two children (in a binary tree). You can't go "up" without following the parent pointer. A binary tree is the special case where every node has at most 2 children: left and right.

Layer 2 โ€” Visual

Binary Tree Structure
          1           โ† Root (Level 0)
        /   \
       2     3        โ† Level 1
      / \     \
     4   5     6      โ† Level 2 (Leaves: 4, 5, 6)

Terminology:
  Root     = 1 (topmost node, no parent)
  Leaf     = 4, 5, 6 (no children)
  Internal = 1, 2, 3 (at least one child)
  Height   = 2 (longest root-to-leaf path)
  Depth(5) = 2 (edges from root to node 5)

Types of Binary Trees

TypePropertyExample Use
Full Binary TreeEvery node has 0 or 2 childrenExpression trees
Complete Binary TreeAll levels filled except possibly the last (filled left-to-right)Binary heaps
Perfect Binary TreeAll internal nodes have 2 children, all leaves at same levelTheoretical ideal
Extended Binary TreeEvery node has exactly 0 or 2 children (same as Full)Huffman coding trees

Memory Representation

Linked Representation (Most Common)
Each node is a struct/class with 3 fields:
โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”ฌโ”€โ”€โ”€โ”€โ”€โ”€โ”ฌโ”€โ”€โ”€โ”€โ”€โ”€โ”
โ”‚ left โ”‚ data โ”‚ rightโ”‚
โ””โ”€โ”€โ”ฌโ”€โ”€โ”€โ”ดโ”€โ”€โ”€โ”€โ”€โ”€โ”ดโ”€โ”€โ”€โ”ฌโ”€โ”€โ”˜
   โ†“              โ†“
 (left child)  (right child)

Sequential (Array) Representation
For node at index i:
  Left child  = 2i + 1
  Right child = 2i + 2
  Parent      = (i - 1) / 2

Index:  0   1   2   3   4   5
Value: [1] [2] [3] [4] [5] [6]

Used for: Binary heaps (complete trees). Wastes space for sparse trees.

2.2 Tree Traversals

The Three Traversal Orders
Tree:       1
          /   \
         2     3
        / \
       4   5

In-order   (Left, Root, Right):  4, 2, 5, 1, 3  โ† Gives SORTED order for BST!
Pre-order  (Root, Left, Right):  1, 2, 4, 5, 3  โ† Used to COPY/SERIALIZE a tree
Post-order (Left, Right, Root):  4, 5, 2, 3, 1  โ† Used to DELETE a tree safely

In-order traversal of a BST always gives sorted output. This is the BST's superpower. If you insert 50, 30, 70, 20, 40, 60, 80 into a BST and do an in-order traversal, you get: 20, 30, 40, 50, 60, 70, 80. Sorted! This is how databases retrieve records "in order" โ€” they traverse a B-Tree in-order.

2.3 Binary Search Tree (BST)

Layer 1 โ€” Intuition

A BST is like a dictionary organized by first letter. If you're looking for "Mango," you open to the middle. "Mango" > "J"? Go right half. "Mango" < "P"? Go left half. Each decision eliminates half the remaining pages โ€” exactly like binary search, but built into the tree structure itself.

Layer 2 โ€” BST Property

BST Property
For EVERY node:
  โ€ข All values in LEFT subtree  < node's value
  โ€ข All values in RIGHT subtree > node's value

        50
       /    \
     30      70       โ† 30 < 50 < 70 โœ“
    /  \    /  \
   20  40  60  80     โ† 20 < 30 < 40 โœ“, 60 < 70 < 80 โœ“

Search for 40:
  50 โ†’ 40 < 50 โ†’ go LEFT
  30 โ†’ 40 > 30 โ†’ go RIGHT
  40 โ†’ FOUND! (3 comparisons for 7 nodes)

Layer 3 โ€” Complexity Table

OperationAverage (Balanced)Worst (Skewed)Space
SearchO(log n)O(n)O(1) iterative / O(h) recursive
InsertO(log n)O(n)Same
DeleteO(log n)O(n)Same
In-order traversalO(n)O(n)O(h) stack
Find Min/MaxO(log n)O(n)O(1)
Real consequence: A balanced BST of Nykaa's 5 million products needs only ~23 comparisons (logโ‚‚ 5M) to find any product. A skewed BST (data inserted in sorted order) degenerates to a linked list and needs 5 million comparisons. This is why databases use self-balancing trees (AVL, Red-Black, B-Trees).

If you insert elements [10, 20, 30, 40, 50] into a BST in that order, what does the tree look like? It becomes a right-skewed linked list! Search becomes O(n). This is why the ORDER of insertion matters, and why self-balancing trees (AVL, Red-Black) exist โ€” they guarantee O(log n) regardless of insertion order.