Python 實現二叉查找樹的示例代碼

二叉查找樹

  • 所有 key 小於 V 的都被存儲在 V 的左子樹
  • 所有 key 大於 V 的都存儲在 V 的右子樹

BST 的節點

class BSTNode(object):
  def __init__(self, key, value, left=None, right=None):
    self.key, self.value, self.left, self.right = key, value, left, right

二叉樹查找

如何查找一個指定的節點呢,根據定義我們知道每個內部節點左子樹的 key 都比它小,右子樹的 key 都比它大,所以 對於帶查找的節點 search_key,從根節點開始,如果 search_key 大於當前 key,就去右子樹查找,否則去左子樹查找

NODE_LIST = [
  {'key': 60, 'left': 12, 'right': 90, 'is_root': True},
  {'key': 12, 'left': 4, 'right': 41, 'is_root': False},
  {'key': 4, 'left': 1, 'right': None, 'is_root': False},
  {'key': 1, 'left': None, 'right': None, 'is_root': False},
  {'key': 41, 'left': 29, 'right': None, 'is_root': False},
  {'key': 29, 'left': 23, 'right': 37, 'is_root': False},
  {'key': 23, 'left': None, 'right': None, 'is_root': False},
  {'key': 37, 'left': None, 'right': None, 'is_root': False},
  {'key': 90, 'left': 71, 'right': 100, 'is_root': False},
  {'key': 71, 'left': None, 'right': 84, 'is_root': False},
  {'key': 100, 'left': None, 'right': None, 'is_root': False},
  {'key': 84, 'left': None, 'right': None, 'is_root': False},
]


class BSTNode(object):
  def __init__(self, key, value, left=None, right=None):
    self.key, self.value, self.left, self.right = key, value, left, right


class BST(object):
  def __init__(self, root=None):
    self.root = root

  @classmethod
  def build_from(cls, node_list):
    cls.size = 0
    key_to_node_dict = {}
    for node_dict in node_list:
      key = node_dict['key']
      key_to_node_dict[key] = BSTNode(key, value=key)  # 這裡值和key一樣的

    for node_dict in node_list:
      key = node_dict['key']
      node = key_to_node_dict[key]
      if node_dict['is_root']:
        root = node
      node.left = key_to_node_dict.get(node_dict['left'])
      node.right = key_to_node_dict.get(node_dict['right'])
      cls.size += 1
    return cls(root)

  def _bst_search(self, subtree, key):
    """
    subtree.key小於key則去右子樹找 因為 左子樹<subtree.key<右子樹
    subtree.key大於key則去左子樹找 因為 左子樹<subtree.key<右子樹
    :param subtree:
    :param key:
    :return:
    """
    if subtree is None:
      return None
    elif subtree.key < key:
      self._bst_search(subtree.right, key)
    elif subtree.key > key:
      self._bst_search(subtree.left, key)
    else:
      return subtree

  def get(self, key, default=None):
    """
    查找樹
    :param key:
    :param default:
    :return:
    """
    node = self._bst_search(self.root, key)
    if node is None:
      return default
    else:
      return node.value

  def _bst_min_node(self, subtree):
    """
    查找最小值的樹
    :param subtree:
    :return:
    """
    if subtree is None:
      return None
    elif subtree.left is None:
      # 找到左子樹的頭
      return subtree
    else:
      return self._bst_min_node(subtree.left)

  def bst_min(self):
    """
    獲取最小樹的value
    :return:
    """
    node = self._bst_min_node(self.root)
    if node is None:
      return None
    else:
      return node.value

  def _bst_max_node(self, subtree):
    """
    查找最大值的樹
    :param subtree:
    :return:
    """
    if subtree is None:
      return None
    elif subtree.right is None:
      # 找到右子樹的頭
      return subtree
    else:
      return self._bst_min_node(subtree.right)

  def bst_max(self):
    """
    獲取最大樹的value
    :return:
    """
    node = self._bst_max_node(self.root)
    if node is None:
      return None
    else:
      return node.value

  def _bst_insert(self, subtree, key, value):
    """
    二叉查找樹插入
    :param subtree:
    :param key:
    :param value:
    :return:
    """
    # 插入的節點一定是根節點,包括 root 為空的情況
    if subtree is None:
      subtree = BSTNode(key, value)
    elif subtree.key > key:
      subtree.left = self._bst_insert(subtree.left, key, value)
    elif subtree.key < key:
      subtree.right = self._bst_insert(subtree.right, key, value)
    return subtree

  def add(self, key, value):
    # 先去查一下看節點是否已存在
    node = self._bst_search(self.root, key)
    if node is not None:
      # 更新已經存在的 key
      node.value = value
      return False
    else:
      self.root = self._bst_insert(self.root, key, value)
      self.size += 1

  def _bst_remove(self, subtree, key):
    """
    刪除並返回根節點
    :param subtree:
    :param key:
    :return:
    """
    if subtree is None:
      return None
    elif subtree.key > key:
      subtree.right = self._bst_remove(subtree.right, key)
      return subtree
    elif subtree.key < key:
      subtree.left = self._bst_remove(subtree.left, key)
      return subtree
    else:
      # 找到瞭需要刪除的節點
      # 要刪除的節點是葉節點 返回 None 把其父親指向它的指針置為 None
      if subtree.left is None and subtree.right is None:
        return None
      # 要刪除的節點有一個孩子
      elif subtree.left is None or subtree.right is None:
        # 返回它的孩子並讓它的父親指過去
        if subtree.left is not None:
          return subtree.left
        else:
          return subtree.right
      else:
        # 有兩個孩子,尋找後繼節點替換,並從待刪節點的右子樹中刪除後繼節點
        # 後繼節點是待刪除節點的右孩子之後的最小節點
        # 中(根)序得到的是一個排列好的列表 後繼節點在待刪除節點的後邊
        successor_node = self._bst_min_node(subtree.right)
        # 用後繼節點替換待刪除節點即可保持二叉查找樹的特性 左<根<右
        subtree.key, subtree.value = successor_node.key, successor_node.value
        # 從待刪除節點的右子樹中刪除後繼節點,並更新其刪除後繼節點後的右子樹
        subtree.right = self._bst_remove(subtree.right, successor_node.key)
        return subtree

  def remove(self, key):
    assert key in self
    self.size -= 1
    return self._bst_remove(self.root, key)

以上就是Python 實現二叉查找樹的示例代碼的詳細內容,更多關於Python 實現二叉查找樹的資料請關註WalkonNet其它相關文章!

推薦閱讀: