# Stacks, Queues, Linked Lists & Binary Tree Properties
Exam: GATE Computer Science & Information Technology (GATE CS)
Subject: Programming & Data Structures
Canonical URL: https://gateandnet.com/exams/gate-cs/programming-and-ds/stacks-queues-linked-lists-and-binary-trees

> Infix/Postfix evaluation, Circular Queue full/empty modular arithmetic, Linked List pointer complexities, Binary Tree degree handshaking lemma, and unique tree reconstruction rules.

## 1. Stacks & Queues Complexity Nuances

- **Stack Applications:** Function activation records, Infix-to-Postfix conversion ($\mathcal{O}(n)$), Postfix evaluation, Stock Span / Next Greater Element ($\mathcal{O}(n)$ monotonic stack), and DFS.
- **Queue Using Two Stacks ($S_1, S_2$):** `Enqueue` pushes to $S_1$ in $\mathcal{O}(1)$; `Dequeue` pops from $S_2$ (transferring $S_1 \to S_2$ only when $S_2$ is empty) $\implies$ **Amortized $\mathcal{O}(1)$** per operation, worst-case single dequeue $\Theta(n)$.
- **Circular Array Queue (size $N$, wasting 1 slot):**
  - Empty: `front == rear`
  - Full: `(rear + 1) % N == front` (holds $N - 1$ elements max unless an explicit `count` is maintained).

## 2. Singly vs Doubly Linked List Complexities

| Operation | Singly LL (Head only) | Singly LL (Head + Tail) | Doubly Linked List |
| :--- | :--- | :--- | :--- |
| Insert at Front / Delete at Front | $\Theta(1)$ | $\Theta(1)$ | $\Theta(1)$ |
| Insert at End | $\Theta(n)$ | $\Theta(1)$ | $\Theta(1)$ (with tail) |
| **Delete Last Node** | $\Theta(n)$ | **$\Theta(n)$ (still needs predecessor!)** | $\Theta(1)$ (with tail) |

## 3. Binary Tree Traversals & Unique Reconstruction

Given two traversals of a binary tree with $n$ distinct keys, when is the tree **uniquely** determined?
- **Inorder + Preorder** $\implies$ **YES (Unique)**
- **Inorder + Postorder** $\implies$ **YES (Unique)**
- **Inorder + Level-Order** $\implies$ **YES (Unique)**
- **Preorder + Postorder** $\implies$ **NO** in general — **YES ONLY IF** the binary tree is **Full/Strict** (every node has $0$ or $2$ children)!
- **BST Only:** A **single Preorder** (or single Postorder) suffices to reconstruct a **BST** uniquely because sorting the keys automatically yields the **Inorder** traversal!

## Solved Practice Questions & PYQs

### [GATE CS DSA | MCQ]
A binary tree has $25$ nodes with degree $2$ (two children) and $12$ nodes with degree $1$. How many **leaf nodes** (degree $0$) does the binary tree contain?
**Correct Answer:** C
**Solution:** In **every** non-empty binary tree, leaf count $n_0 = n_2 + 1$ (degree-1 nodes $n_1$ cancel out of $\sum \text{deg} = N - 1$!). Thus $n_0 = 25 + 1 = \mathbf{26}$.

### [GATE CS DSA | MCQ]
Evaluate the postfix (Reverse Polish) expression: `8 2 3 ^ / 2 3 * + 5 1 * -` where `^` denotes exponentiation.
**Correct Answer:** A
**Solution:** Step-by-step stack trace: `2 3 ^` $= 2^3 = 8$; `8 8 /` $= 1$; `2 3 *` $= 6$; `1 6 +` $= 7$; `5 1 *` $= 5$; `7 5 -` $= \mathbf{2}$.
