---
id: wiki-2026-0508-linked-lists-and-trees
title: Linked Lists and Trees
category: 10_Wiki/Topics
status: verified
canonical_id: self
aliases: [Linked List, Tree, 연결 리스트, 트리]
duplicate_of: none
source_trust_level: A
confidence_score: 0.92
verification_status: applied
tags: [data-structures, linked-list, tree, fundamentals]
raw_sources: []
last_reinforced: 2026-05-10
github_commit: pending
tech_stack:
  language: python
  framework: none
---

# Linked Lists and Trees

## 매 한 줄
> **"매 pointer-based dynamic structure 의 family: 매 1D (list) → 매 hierarchy (tree)"**. 매 1955 Newell-Shaw-Simon 의 IPL 의 origin. 매 modern era 의 in-memory 의 array/hash 의 dominant — 매 list/tree 의 specific use (cache-unfriendly 의 의 X).

## 매 핵심

### 매 Linked List
- **node**: data + next pointer.
- **singly**: O(1) head insert, O(n) random access, O(n) delete by value.
- **doubly**: prev + next — O(1) delete with node pointer.
- **circular**: tail.next = head.
- **memory**: 매 cache-unfriendly (pointer chasing).

### 매 Tree
- **rooted tree**: parent + children, 매 root 의 single.
- **binary tree**: ≤ 2 children.
- **BST**: left < root < right — search O(h), 매 worst h = n (degenerate).
- **balanced (RB, AVL, Splay)**: h = O(log n).
- **traversal**: pre-order (root-left-right), in-order (left-root-right = sorted for BST), post-order, level-order (BFS).

### 매 modern relevance
- **list 의 X**: 매 dynamic array (Vec / list) 의 의 의 amortized O(1) append + O(1) random access + cache-friendly.
- **tree 의 use case**: 매 sorted + range query (RB, B+ tree), 매 hierarchy (DOM, AST, filesystem), 매 priority (heap).

### 매 응용
1. AST (compiler).
2. DOM (browser).
3. Filesystem (directory tree).
4. Decision tree (ML).
5. Priority queue (heap = array-backed binary tree).

## 💻 패턴

### Singly linked list
```python
class Node:
    __slots__ = ('val', 'next')
    def __init__(self, val, next=None):
        self.val = val; self.next = next

class LinkedList:
    def __init__(self):
        self.head = None
    def push(self, val):  # O(1) head insert
        self.head = Node(val, self.head)
    def find(self, val):  # O(n)
        n = self.head
        while n:
            if n.val == val: return n
            n = n.next
        return None
    def reverse(self):  # O(n) in-place
        prev, curr = None, self.head
        while curr:
            curr.next, prev, curr = prev, curr, curr.next
        self.head = prev
```

### Detect cycle (Floyd's tortoise & hare)
```python
def has_cycle(head: Node) -> bool:
    slow = fast = head
    while fast and fast.next:
        slow = slow.next
        fast = fast.next.next
        if slow is fast:
            return True
    return False
```

### Binary tree traversal
```python
class TreeNode:
    def __init__(self, val, left=None, right=None):
        self.val, self.left, self.right = val, left, right

def inorder(node):  # sorted output for BST
    if not node: return
    yield from inorder(node.left)
    yield node.val
    yield from inorder(node.right)

def level_order(root):  # BFS
    from collections import deque
    if not root: return
    q = deque([root])
    while q:
        node = q.popleft()
        yield node.val
        if node.left: q.append(node.left)
        if node.right: q.append(node.right)
```

### BST insert / search
```python
class BST:
    def __init__(self): self.root = None

    def insert(self, val):
        def _ins(node):
            if not node: return TreeNode(val)
            if val < node.val: node.left = _ins(node.left)
            elif val > node.val: node.right = _ins(node.right)
            return node
        self.root = _ins(self.root)

    def search(self, val) -> bool:
        n = self.root
        while n:
            if val == n.val: return True
            n = n.left if val < n.val else n.right
        return False
```

### LRU cache (doubly linked list + dict)
```python
class LRUCache:
    class Node:
        __slots__ = ('k', 'v', 'prev', 'nxt')
        def __init__(self, k, v): self.k, self.v, self.prev, self.nxt = k, v, None, None

    def __init__(self, cap):
        self.cap = cap; self.map = {}
        self.head = self.Node(0, 0); self.tail = self.Node(0, 0)
        self.head.nxt = self.tail; self.tail.prev = self.head

    def _remove(self, n):
        n.prev.nxt = n.nxt; n.nxt.prev = n.prev

    def _add_front(self, n):
        n.nxt = self.head.nxt; n.prev = self.head
        self.head.nxt.prev = n; self.head.nxt = n

    def get(self, k):
        if k not in self.map: return -1
        n = self.map[k]
        self._remove(n); self._add_front(n)
        return n.v

    def put(self, k, v):
        if k in self.map:
            self._remove(self.map[k])
        elif len(self.map) >= self.cap:
            lru = self.tail.prev
            self._remove(lru); del self.map[lru.k]
        n = self.Node(k, v); self.map[k] = n
        self._add_front(n)
```

### Tree height + balance check
```python
def height(node):
    if not node: return 0
    return 1 + max(height(node.left), height(node.right))

def is_balanced(node) -> bool:
    def check(n):
        if not n: return 0  # height
        l = check(n.left)
        if l == -1: return -1
        r = check(n.right)
        if r == -1 or abs(l - r) > 1: return -1
        return 1 + max(l, r)
    return check(node) != -1
```

## 매 결정 기준
| 상황 | Approach |
|---|---|
| 매 random access | array / dynamic array (NOT list) |
| 매 head insert frequent | linked list |
| 매 LRU eviction | doubly linked list + dict |
| 매 sorted + range | balanced BST / B+ tree |
| 매 priority | binary heap (array-backed) |
| 매 hierarchy (DOM, AST) | n-ary tree |
| 매 unique key lookup | hash map |
| 매 prefix search | trie |

**기본값**: list 의 X — dynamic array 의 의. tree 의 specific structure (BST sorted, heap priority, n-ary hierarchy) 의 의.

## 🔗 Graph
- 변형: [[Skip List]]
- 응용: [[AST Abstract Syntax Tree]] · [[DOM Tree]]
- Adjacent: [[Hash Functions and Maps]] · [[B-Tree]] · [[Trie]]

## 🤖 LLM 활용
**언제**: 매 hierarchy 의 model (AST, DOM, filesystem), 매 LRU 의 doubly linked, 매 BST 의 sorted lookup, 매 trie 의 prefix.
**언제 X**: 매 1D index access (array), 매 unique lookup (hash), 매 cache-sensitive scan (array), 매 small data (overhead 의 X).

## ❌ 안티패턴
- **list 의 random access**: O(n) — 매 array 의 의.
- **BST 의 unbalanced**: 매 sorted insert → O(n) height. 매 RB / AVL 의 의.
- **memory leak**: 매 unlink X / cycle 의 reference → GC 의 fail (in C, manual free needed).
- **shallow copy**: 매 tree clone 의 deep copy 의 의 — `copy.deepcopy` 의 의.
- **recursion depth**: 매 deep tree 의 stack overflow — iterative + explicit stack 의 의.

## 🧪 검증 / 중복
- Verified (CLRS Ch 10, 12; Sedgewick Algorithms 4th).
- 신뢰도 A.

## 🕓 Changelog
| 날짜 | 변경 |
|---|---|
| 2026-05-08 | Phase 1 |
| 2026-05-10 | Manual cleanup — linked list + tree fundamentals with LRU + Floyd cycle |
