open-courses
  • 公开课笔记
  • CMU 15-445/645 Database Systems
    • Relational Data Model
    • Advanced SQL
    • Database Storage
    • Buffer Pools
    • Hash Tables
    • Tree Indexes
    • Index Concurrency Control
    • Query Processing
    • Sorting&Aggregations
    • Join Algorithms
    • Query Optimization
    • Parallel Execution
    • Embedded Database Logic
    • Concurrency Control Theory
    • Two Phase Locking
    • Timestamp Ordering Concurrency Control
    • Multi-Version Concurrency Control
    • Logging Schemes
    • Database Recovery
    • Introduction to Distributed Databases
    • Distributed OLTP Databases
    • Distributed OLAP Databases
  • UCB - CS162
    • OS intro
    • Introduction to the Process
    • Processes, Fork, I/O, Files
    • I/O Continued, Sockets, Networking
    • Concurrency: Processes & Threads
    • Cooperating Threads, Synchronization
    • Semaphores, Condition Variables, Readers/Writers
    • Scheduling
    • Resource Contention & Deadlock
    • Address Translation, Caching
    • File System (18,19,20)
    • Distributed Systems, Networking, TCP/IP, RPC (21,22)
    • Distributed Storage, Key-Value Stores, Security (23)
    • Security & Cloud Computing (24)
    • Topic: Ensuring Data Reaches Disk
  • MIT - 6.006
    • Sequence and Set Interface
    • Data Structure for Dynamic Sequence Interface
    • Computation Complexity
    • Algorithms and Computation
    • Structure Of Computation
    • Graph & Search
    • Tree & Search
    • Weighted Shortest Paths
    • String Matching, Karp-Rabin
    • Priority Queue Interface & Implementation
    • Dictionary Problem & Implementation
    • Sorting
    • Dynamic Programming
    • Backtracking
    • Self-Balancing Tree
  • MIT - 6.824
    • 2PC & 3PC
    • Introduction and MapReduce
    • RPC and Threads
    • Primary/Backup Replication
    • Lab: Primary/Backup Key/Value Service
    • Google File System (GFS)
    • Raft
    • Lab: Raft - Leader Election
    • Lab: Raft - Log Replication
  • Stanford-CS107
    • 原始数据类型及相互转化
    • 指鹿为马
    • 泛型函数
    • 泛型栈
    • 运行时内存结构
    • 从 C 到汇编
    • 函数的活动记录
    • C 与 C++ 代码生成
    • 编译的预处理过程
    • 编译的链接过程
    • 函数的活动记录续、并发
    • 从顺序到并发和并行
    • 信号量与多线程 1
    • 信号量与多线程 2
    • 复杂多线程问题
    • 函数式编程 - Scheme 1
    • 函数式编程 - Scheme 2
    • 函数式编程 - Scheme 3
    • 函数式编程 - Scheme 4
    • 函数式编程 - Scheme 5
    • Python 基础
  • MIT - 6.001 - SICP
    • 什么是程序
    • 程序抽象
    • 替代模型
    • 时间/空间复杂度
    • 数据抽象
    • 高阶函数
    • Symbol
    • 数据驱动编程与防御式编程
    • 数据抽象中的效率与可读性
    • 数据修改
    • 环境模型
    • 面向对象-消息传递
    • 面向对象 - Scheme 实现
    • 构建 Scheme 解释器
    • Eval-Apply Loop
    • Normal Order (Lazy) Evaluation
    • 通用机
    • 寄存器机器
    • 子程序、栈与递归
    • 在寄存器机器中执行
    • 内存管理
  • MIT - 6.046
    • Randomized Algorithms
    • Skip Lists
  • System Design
    • Twitter
    • Cache Consistency & Coherence
  • DDIA 笔记
    • Replication
    • Transactions
    • The Trouble with Distributed Systems
    • Consistency & Consensus
  • Papers We Love
    • Consistent Hashing and Random Trees (1997)
    • Dynamic Hash Tables (1988)
    • LFU Implementation With O(1) Complexity (2010)
    • Time, Clocks, and the Ordering of Events in a Distributed System (1978)
    • Dapper, a Large-Scale Distributed Systems Tracing Infrastructure (2010)
    • Gorilla: A Fast, Scalable, In-Memory Time Series Database (2015)
  • Release It 笔记
    • Anti-patterns & Patterns in Microservice Architecture
  • Database Design
    • Log Structured Merge (LSM) Tree & Usages in KV Stores
    • Prometheus
Powered by GitBook
On this page
  • Binary Tree
  • Tree Representation
  • Tree Search
  • Binary Search Tree (BST)
  1. MIT - 6.006

Tree & Search

树以及树搜索算法

本节内容为自己整理,是 Graph & Search 的子集。示例中皆假设不同节点的值不同。

Binary Tree

Tree Representation

class TreeNode:
    def __init__(self, val):
        self.val = val
        self.left = None
        self.right = None

Tree Search

Depth First Search (DFS)

方法 1:使用递归

def dfs(root):
    if not root:
        return
    # preorder: action on root.val
    left_val = dfs(root.left)
    # inorder: action on root.val
    right_val = dfs(root.right
    # postorder: action on root.val
    return func(left_val, right_val)

方法 2:使用栈迭代

def dfs_preorder(node):
    if not node:
        return
    stack = [node]
    while stack:
        node = stack.pop()
        # from right to left
        if node.right:
            stack.append(node.right)
        if node.left:
            stack.append(node.left)

def dfs_postorder(node):
    if not node:
        return
    stack = [node]
    
    ret = []
    while stack:
        node = stack.pop()
        ret.append(node.val)
        if node.left:
            stack.append(node.left)
        if node.right:
            stack.append(node.right)
    return ret[::-1]

Breadth First Search (BFS)

方法1:使用 list

def bfs(root):
    if not root:
        return
    q = [root]
    while q:
        nq = []
        for node in q:
            if node.left:
                nq.append(node.left)
            if node.right:
                nq.append(node.right)
        q = nq

方法2:使用 dequeue

from collections import dequeue
def bfs(root):
    if not root:
        return
    q = dequeue([root])
    while q:
        node = q.popleft()
        if node.left:
            q.append(node.left)
        if node.right:
            q.append(node.right)

Binary Search Tree (BST)

BST 是一种特殊的 Binary Tree,其中任意节点都满足:

  • 左子树中所有节点的值都小于当前节点的值

  • 右子树中所有节点的值都大于当前节点的值

BST 的一些特性罗列如下:

  • 通过 in-order traversal 可以得到所有节点按 key 排序的结果

  • 擅长做一些特殊查询

    • 查询与某 key 大小最相近的元素(closest lower/greater elements)

    • 区间查询(range queries)

  • 如果是 Self-Balancing BST(Red-Black Tree, AVL Tree, Splay Tree)则所有操作的复杂度为 θ(logn)\theta(logn)θ(logn)

Search

def search(root, key):
    if root is None or root.val == key:
        return root
    if root.val < key:
        return search(root.right, key)
    return search(root.left, key)

Time complexity: O(h)O(h)O(h)

Insertion

def insert(root, node):
    if root is None:
        root = node
    else:
        if roo.val < node.val:
            if root.right is None:
                root.right = node
            else:
                insert(root.right, node)
        else:
            if root.left is None:
                root.left = node
            else:
                insert(root.left, node)

Time complexity: O(h)O(h)O(h)

Deletion

删除的时候分三种情况考虑:

  1. 如果是 leaf node:直接删除

  2. 如果只有一个 child:交换两个节点的值,并把 child node 删了

  3. 如果有两个 children:找到 inorder 遍历的下一个 node,交换两个节点的值,并把下一个 node 删除

# Given a non-empty binary search tree, return the node
# with minimum key value found in that tree.
def minValueNode(node):
    current = node
    while current.left is not None:
        current = current.left
    return current

def deleteNode(root, key):
    if root is None:
        return root
    if key < root.key:
        root.left = deleteNode(root.left, key)
    elif key > root.key:
        root.right = deleteNode(root.right, key)
    else:
        if root.left is None:
            root = root.right
            return root
        elif root.right is None:
            root = root.left
            return root
        next_node = minValueNode(root.right)
        root.key = next_node.key
        root.right = deleteNode(root.right, next_node.key)
    return root  

Time complexity: O(h)O(h)O(h)

Traversal

  • In-order traversal of BST always produces sorted output

  • we can construct a BST with only Preorder or Postorder or Level Order traversal.

  • number of unique BSTs with n distinct keys is Catalan Number

算法题集锦:

  • Search

  • Pre-order Traversal

  • In-order Traversal

  • Post-order Traversal:

  • Breadth First/Level Order Search

  • Construction

  • Complete Tree

  • Dynamic Programming

  • Graph Search

PreviousGraph & SearchNextWeighted Shortest Paths

Last updated 6 years ago

Search in a Binary Search Tree
Print Binary Tree
Maximum Binary Tree
Invert Binary Tree
Binary Tree Paths
Second Minimum Node In a Binary Tree
Find Mode in Binary Search Tree
Verify Preorder Serialization of a Binary Tree
Merge Two Binary Trees
Binary Tree Preorder Traversal
Flatten Binary Tree to Linked List
Binary Tree In-order Traversal
Validate Binary Search Tree
Increasing Order SearchTree
Binary Tree Tilt
Univalued Binary Tree
Diameter of Binary Tree
Binary Tree Cameras
Binary Tree Pruning
Unique Binary Search Trees II
Binary Tree Maximum Path Sum
Maximum Width of Binary Tree
Binary Tree Right Side View
Binary Tree Level Order Traversal II
Convert Sorted List to Binary Search Tree
Construct Binary Tree from In-order and Post-order Traversal
Count Complete Tree Node
Unique Binary Search Trees
All Nodes Distance K in Binary Tree