什么是二叉树

每个节点最多有两个子节点(左子、右子)的树形结构。像倒过来的树。

     1
    / \
   2   3
  / \
 4   5

三种遍历

遍历方式顺序上面例子输出
前序遍历根→左→右1,2,4,5,3
中序遍历左→根→右4,2,5,1,3
后序遍历左→右→根4,5,2,3,1

Python 实现

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)

一种特殊的二叉树:左子树所有节点 < 根节点 < 右子树所有节点。

关键性质:中序遍历 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)

BST 的意义

查找、插入、删除都是 O(log n)(平衡时),比数组 O(n) 或链表 O(n) 快得多。数据库索引(B+树)就是 BST 的改进版。

注意:如果 BST 插入顺序是 1,2,3,4,5,它会退化成链表,查找变成 O(n)。这就是为什么实际用的是平衡树(AVL、红黑树)。