Skip to Content

Cây (Tree)

Tree là gì?

Tree là cấu trúc dữ liệu phi tuyến tính gồm các node được kết nối theo quan hệ cha-con, bắt đầu từ root.

1 ← Root / | \ 2 3 4 ← Children / \ 5 6 ← Leaves
💡

Tree giống như cây gia phả hoặc tổ chức thư mục trên máy tính!

Cài đặt Binary Tree Node

class TreeNode: def __init__(self, val): self.val = val self.left = None self.right = None # Tạo cây root = TreeNode(1) root.left = TreeNode(2) root.right = TreeNode(3)

Duyệt cây (Inorder: Left - Root - Right)

def inorder(root): if root: inorder(root.left) print(root.val, end=" ") inorder(root.right)

Level Order Traversal (BFS)

from collections import deque def level_order(root): if not root: return [] result = [] queue = deque([root]) while queue: level = [] for _ in range(len(queue)): node = queue.popleft() level.append(node.val) if node.left: queue.append(node.left) if node.right: queue.append(node.right) result.append(level) return result

Chiều cao của cây

def height(root): if not root: return 0 return 1 + max(height(root.left), height(root.right))

Ứng dụng thực tế

Ứng dụngMô tả
File systemCấu trúc thư mục
DOMCấu trúc trang web
DatabaseB-tree, indexing
CompilerAbstract Syntax Tree

Tiếp theo: Heap & Priority Queue

Last updated on