💻 Programming

Tree

Tree

A hierarchical data structure. Binary tree, BST, AVL, B-Tree. Used in search, sorting, the DOM, and file systems.

📖 Detailed Explanation

A Tree is a hierarchical data structure composed of nodes and edges. Starting from the topmost node, the root, it branches out to child nodes, and it is a connected graph with no cycles. Each node holds data and references to its child nodes, and forms a hierarchy through parent-child relationships. The structure of a tree is described with concepts such as depth, height, and level.

Types of trees: A binary tree is the basic form in which each node has at most 2 children. A binary search tree (BST) is ordered by the rule left child < parent < right child. AVL trees and Red-Black trees are self-balancing trees that guarantee O(log n) performance. B-Trees and B+ Trees are optimized for disk-based storage and are used for database indexes.

Time complexity: A general BST is O(log n) on average, but degrades to O(n) when it becomes skewed. AVL/Red-Black trees always guarantee O(log n). A B-Tree minimizes disk I/O, making it efficient for large volumes of data. A heap is a complete binary tree with O(log n) insertion/deletion and O(1) min/max lookup.

Practical use: The DOM (Document Object Model) of a web browser represents HTML as a tree structure. File systems manage directory-file relationships as a tree. A database's B+ Tree index enables millisecond-level searches across millions of records. In AI/ML, it is widely used to represent decision trees and decision-making processes.

📊 Time Complexity Comparison

A comparison of the time complexity of operations by tree type.

Tree Type Search Insert Delete Space
BST (Average) O(log n) O(log n) O(log n) O(n)
BST (Worst) O(n) O(n) O(n) O(n)
AVL / Red-Black O(log n) O(log n) O(log n) O(n)
B-Tree O(log n) O(log n) O(log n) O(n)
Heap O(n) O(log n) O(log n) O(n)

Selection criteria: Use AVL/Red-Black if memory-based search is the main purpose, B-Tree if there is a lot of disk I/O, and Heap if priority handling is needed.

💻 Code Example

# 이진 탐색 트리 (BST) 구현
class TreeNode:
    def __init__(self, val):
        self.val = val
        self.left = None
        self.right = None

class BST:
    def __init__(self):
        self.root = None

    # 삽입 - O(log n) 평균, O(n) 최악
    def insert(self, val):
        if not self.root:
            self.root = TreeNode(val)
            return

        def _insert(node, val):
            if val < node.val:
                if node.left is None:
                    node.left = TreeNode(val)
                else:
                    _insert(node.left, val)
            else:
                if node.right is None:
                    node.right = TreeNode(val)
                else:
                    _insert(node.right, val)

        _insert(self.root, val)

    # 검색 - O(log n) 평균
    def search(self, val):
        def _search(node, val):
            if node is None or node.val == val:
                return node
            if val < node.val:
                return _search(node.left, val)
            return _search(node.right, val)

        return _search(self.root, val)

    # 트리 순회 (Traversal)
    def inorder(self, node, result=None):
        """중위 순회: 왼쪽 → 루트 → 오른쪽 (정렬된 순서)"""
        if result is None:
            result = []
        if node:
            self.inorder(node.left, result)
            result.append(node.val)
            self.inorder(node.right, result)
        return result

    def preorder(self, node, result=None):
        """전위 순회: 루트 → 왼쪽 → 오른쪽 (복사에 유용)"""
        if result is None:
            result = []
        if node:
            result.append(node.val)
            self.preorder(node.left, result)
            self.preorder(node.right, result)
        return result

    def postorder(self, node, result=None):
        """후위 순회: 왼쪽 → 오른쪽 → 루트 (삭제에 유용)"""
        if result is None:
            result = []
        if node:
            self.postorder(node.left, result)
            self.postorder(node.right, result)
            result.append(node.val)
        return result

    # 레벨 순회 (BFS)
    def level_order(self):
        """너비 우선 탐색: 레벨별로 순회"""
        from collections import deque
        if not self.root:
            return []

        result = []
        queue = deque([self.root])

        while queue:
            node = queue.popleft()
            result.append(node.val)
            if node.left:
                queue.append(node.left)
            if node.right:
                queue.append(node.right)

        return result

# 사용 예시
bst = BST()
for val in [50, 30, 70, 20, 40, 60, 80]:
    bst.insert(val)

print("중위 순회:", bst.inorder(bst.root))    # [20, 30, 40, 50, 60, 70, 80]
print("전위 순회:", bst.preorder(bst.root))   # [50, 30, 20, 40, 70, 60, 80]
print("레벨 순회:", bst.level_order())         # [50, 30, 70, 20, 40, 60, 80]

# 검색
node = bst.search(40)
print(f"검색 결과: {node.val if node else 'Not found'}")  # 40
// 이진 탐색 트리 (BST) 구현
class TreeNode {
    constructor(val) {
        this.val = val;
        this.left = null;
        this.right = null;
    }
}

class BST {
    constructor() {
        this.root = null;
    }

    // 삽입
    insert(val) {
        const newNode = new TreeNode(val);
        if (!this.root) {
            this.root = newNode;
            return;
        }

        let current = this.root;
        while (true) {
            if (val < current.val) {
                if (!current.left) {
                    current.left = newNode;
                    break;
                }
                current = current.left;
            } else {
                if (!current.right) {
                    current.right = newNode;
                    break;
                }
                current = current.right;
            }
        }
    }

    // 검색
    search(val) {
        let current = this.root;
        while (current) {
            if (val === current.val) return current;
            current = val < current.val ? current.left : current.right;
        }
        return null;
    }

    // 중위 순회 (정렬된 결과)
    inorder(node = this.root, result = []) {
        if (node) {
            this.inorder(node.left, result);
            result.push(node.val);
            this.inorder(node.right, result);
        }
        return result;
    }

    // 레벨 순회 (BFS)
    levelOrder() {
        if (!this.root) return [];

        const result = [];
        const queue = [this.root];

        while (queue.length > 0) {
            const node = queue.shift();
            result.push(node.val);
            if (node.left) queue.push(node.left);
            if (node.right) queue.push(node.right);
        }

        return result;
    }

    // 트리 높이
    getHeight(node = this.root) {
        if (!node) return -1;
        return 1 + Math.max(
            this.getHeight(node.left),
            this.getHeight(node.right)
        );
    }
}

// 사용 예시
const bst = new BST();
[50, 30, 70, 20, 40, 60, 80].forEach(val => bst.insert(val));

console.log('중위 순회:', bst.inorder());      // [20, 30, 40, 50, 60, 70, 80]
console.log('레벨 순회:', bst.levelOrder());   // [50, 30, 70, 20, 40, 60, 80]
console.log('트리 높이:', bst.getHeight());    // 2

// DOM 트리 순회 예시 (실무)
function traverseDOM(element, depth = 0) {
    console.log('  '.repeat(depth) + element.tagName);
    for (const child of element.children) {
        traverseDOM(child, depth + 1);
    }
}
// traverseDOM(document.body);
import java.util.*;

// 이진 탐색 트리 (BST) 구현
class TreeNode {
    int val;
    TreeNode left, right;

    TreeNode(int val) {
        this.val = val;
        this.left = null;
        this.right = null;
    }
}

class BST {
    private TreeNode root;

    // 삽입
    public void insert(int val) {
        root = insertRec(root, val);
    }

    private TreeNode insertRec(TreeNode node, int val) {
        if (node == null) {
            return new TreeNode(val);
        }
        if (val < node.val) {
            node.left = insertRec(node.left, val);
        } else {
            node.right = insertRec(node.right, val);
        }
        return node;
    }

    // 검색
    public TreeNode search(int val) {
        return searchRec(root, val);
    }

    private TreeNode searchRec(TreeNode node, int val) {
        if (node == null || node.val == val) {
            return node;
        }
        return val < node.val
            ? searchRec(node.left, val)
            : searchRec(node.right, val);
    }

    // 중위 순회
    public List inorder() {
        List result = new ArrayList<>();
        inorderRec(root, result);
        return result;
    }

    private void inorderRec(TreeNode node, List result) {
        if (node != null) {
            inorderRec(node.left, result);
            result.add(node.val);
            inorderRec(node.right, result);
        }
    }

    // 레벨 순회 (BFS)
    public List levelOrder() {
        List result = new ArrayList<>();
        if (root == null) return result;

        Queue queue = new LinkedList<>();
        queue.offer(root);

        while (!queue.isEmpty()) {
            TreeNode node = queue.poll();
            result.add(node.val);
            if (node.left != null) queue.offer(node.left);
            if (node.right != null) queue.offer(node.right);
        }

        return result;
    }

    public static void main(String[] args) {
        BST bst = new BST();
        int[] values = {50, 30, 70, 20, 40, 60, 80};

        for (int val : values) {
            bst.insert(val);
        }

        System.out.println("중위 순회: " + bst.inorder());
        // [20, 30, 40, 50, 60, 70, 80]

        System.out.println("레벨 순회: " + bst.levelOrder());
        // [50, 30, 70, 20, 40, 60, 80]

        TreeNode found = bst.search(40);
        System.out.println("검색 결과: " + (found != null ? found.val : "Not found"));
    }
}

🗣️ Say It Like This in Practice

💬 In an Interview - BST vs Hash Table
"Both BST and Hash Table are used for searching, but their characteristics differ. A Hash Table offers O(1) search on average but does not guarantee order, while a BST offers O(log n) but allows traversal in sorted order. If range queries or min/max values are frequently needed, choose a BST (or TreeMap); if simple key-value lookup is the main purpose, choose a Hash Table."
💬 In a Design Meeting - Choosing a Tree Structure
"We need to store the user category hierarchy. It is about 5 levels deep, and categories are moved frequently. A Nested Set is fast for lookups but requires bulk updates on moves, so a Materialized Path or Closure Table seems more suitable. Since the number of categories is under 10,000, we'll go with the Closure Table."
💬 In a code review
"Here, inserting sorted data into a BST sequentially results in a skewed tree, making searches O(n). If you use TreeSet or TreeMap, they are internally Red-Black trees, so balance is maintained automatically. Alternatively, you could shuffle the data before inserting it."

Take a mock interview on this topic → WIA SOOM AI Interview · Start for free

⚠️ Common Mistakes & Cautions

❌
Ignoring Balance Maintenance

Inserting sorted data into a general BST makes it skewed like a linked list, giving O(n) performance. Use AVL or Red-Black trees, or shuffle the data before inserting it.

❌
Exceeding Recursion Depth (Stack Overflow)

Recursive traversal of a deep tree can cause a stack overflow. If the depth is 1000 or more, use a loop with an explicit stack, or in Python, adjust sys.setrecursionlimit().

❌
Underestimating Memory Usage

Tree nodes store pointers (references) in addition to data. A binary tree with n nodes uses 2n pointers (including null). For large volumes of data, a structure that stores multiple keys per node, like a B-Tree, is more efficient.

✅
The right approach

Choose a tree that fits the purpose: AVL/Red-Black for in-memory search, B-Tree for disk-based, Heap for priority. Make active use of standard libraries (Java TreeMap, C++ std::map, Python sortedcontainers).

🔗 Related Terms

📚 Learn More