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
Python
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)
Python
def inorder(root):
if root:
inorder(root.left)
print(root.val, end=" ")
inorder(root.right)Level Order Traversal (BFS)
Python
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 resultChiều cao của cây
Python
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ụng | Mô tả |
|---|---|
| File system | Cấu trúc thư mục |
| DOM | Cấu trúc trang web |
| Database | B-tree, indexing |
| Compiler | Abstract Syntax Tree |
Tiếp theo: Heap & Priority Queue
Last updated on