每个节点最多有两个子节点(左子、右子)的树形结构。像倒过来的树。
1
/ \
2 3
/ \
4 5
| 遍历方式 | 顺序 | 上面例子输出 |
|---|---|---|
| 前序遍历 | 根→左→右 | 1,2,4,5,3 |
| 中序遍历 | 左→根→右 | 4,2,5,1,3 |
| 后序遍历 | 左→右→根 | 4,5,2,3,1 |
class TreeNode:
def __init__(self, val):
self.val = val
self.left = None
self.right = None
# 递归前序遍历
def preorder(root):
if not root: return []
return [root.val] + preorder(root.left) + preorder(root.right)
# 递归中序遍历
def inorder(root):
if not root: return []
return inorder(root.left) + [root.val] + inorder(root.right)
一种特殊的二叉树:左子树所有节点 < 根节点 < 右子树所有节点。
关键性质:中序遍历 BST 得到升序序列。
def search_bst(root, target):
if not root: return None
if root.val == target: return root
if target < root.val:
return search_bst(root.left, target)
else:
return search_bst(root.right, target)
查找、插入、删除都是 O(log n)(平衡时),比数组 O(n) 或链表 O(n) 快得多。数据库索引(B+树)就是 BST 的改进版。
注意:如果 BST 插入顺序是 1,2,3,4,5,它会退化成链表,查找变成 O(n)。这就是为什么实际用的是平衡树(AVL、红黑树)。