欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

Python 實(shí)現(xiàn)二叉查找樹的示例代碼

 更新時(shí)間:2020年12月21日 15:40:20   作者:_慕  
這篇文章主要介紹了Python 實(shí)現(xiàn)二叉查找樹的示例代碼,幫助大家更好的理解和使用python,感興趣的朋友可以了解下

二叉查找樹

  • 所有 key 小于 V 的都被存儲(chǔ)在 V 的左子樹
  • 所有 key 大于 V 的都存儲(chǔ)在 V 的右子樹

BST 的節(jié)點(diǎn)

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

二叉樹查找

如何查找一個(gè)指定的節(jié)點(diǎn)呢,根據(jù)定義我們知道每個(gè)內(nèi)部節(jié)點(diǎn)左子樹的 key 都比它小,右子樹的 key 都比它大,所以 對于帶查找的節(jié)點(diǎn) search_key,從根節(jié)點(diǎn)開始,如果 search_key 大于當(dāng)前 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則去右子樹找 因?yàn)?左子樹<subtree.key<右子樹
    subtree.key大于key則去左子樹找 因?yàn)?左子樹<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:
    """
    # 插入的節(jié)點(diǎn)一定是根節(jié)點(diǎn),包括 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):
    # 先去查一下看節(jié)點(diǎn)是否已存在
    node = self._bst_search(self.root, key)
    if node is not None:
      # 更新已經(jīng)存在的 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):
    """
    刪除并返回根節(jié)點(diǎn)
    :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:
      # 找到了需要?jiǎng)h除的節(jié)點(diǎn)
      # 要?jiǎng)h除的節(jié)點(diǎn)是葉節(jié)點(diǎn) 返回 None 把其父親指向它的指針置為 None
      if subtree.left is None and subtree.right is None:
        return None
      # 要?jiǎng)h除的節(jié)點(diǎn)有一個(gè)孩子
      elif subtree.left is None or subtree.right is None:
        # 返回它的孩子并讓它的父親指過去
        if subtree.left is not None:
          return subtree.left
        else:
          return subtree.right
      else:
        # 有兩個(gè)孩子,尋找后繼節(jié)點(diǎn)替換,并從待刪節(jié)點(diǎn)的右子樹中刪除后繼節(jié)點(diǎn)
        # 后繼節(jié)點(diǎn)是待刪除節(jié)點(diǎn)的右孩子之后的最小節(jié)點(diǎn)
        # 中(根)序得到的是一個(gè)排列好的列表 后繼節(jié)點(diǎn)在待刪除節(jié)點(diǎn)的后邊
        successor_node = self._bst_min_node(subtree.right)
        # 用后繼節(jié)點(diǎn)替換待刪除節(jié)點(diǎn)即可保持二叉查找樹的特性 左<根<右
        subtree.key, subtree.value = successor_node.key, successor_node.value
        # 從待刪除節(jié)點(diǎn)的右子樹中刪除后繼節(jié)點(diǎn),并更新其刪除后繼節(jié)點(diǎn)后的右子樹
        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 實(shí)現(xiàn)二叉查找樹的示例代碼的詳細(xì)內(nèi)容,更多關(guān)于Python 實(shí)現(xiàn)二叉查找樹的資料請關(guān)注腳本之家其它相關(guān)文章!

相關(guān)文章

  • python使用paramiko執(zhí)行服務(wù)器腳本并拿到實(shí)時(shí)結(jié)果

    python使用paramiko執(zhí)行服務(wù)器腳本并拿到實(shí)時(shí)結(jié)果

    這篇文章主要介紹了python使用paramiko執(zhí)行服務(wù)器腳本并拿到實(shí)時(shí)結(jié)果,具有很好的參考價(jià)值,希望對大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2022-12-12
  • Python 字典一個(gè)鍵對應(yīng)多個(gè)值的方法

    Python 字典一個(gè)鍵對應(yīng)多個(gè)值的方法

    這篇文章主要介紹了Python 字典一個(gè)鍵對應(yīng)多個(gè)值的方法,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2020-09-09
  • python根據(jù)出生日期返回年齡的方法

    python根據(jù)出生日期返回年齡的方法

    這篇文章主要介紹了python根據(jù)出生日期返回年齡的方法,實(shí)例分析了Python時(shí)間操作的技巧,非常具有實(shí)用價(jià)值,需要的朋友可以參考下
    2015-03-03
  • 用Python監(jiān)控NASA TV直播畫面的實(shí)現(xiàn)步驟

    用Python監(jiān)控NASA TV直播畫面的實(shí)現(xiàn)步驟

    本文分享一個(gè)名為"Spacestills"的開源程序,它可以用于查看 NASA TV 的直播畫面(靜止幀)
    2021-05-05
  • 對pandas里的loc并列條件索引的實(shí)例講解

    對pandas里的loc并列條件索引的實(shí)例講解

    今天小編就為大家分享一篇對pandas里的loc并列條件索引的實(shí)例講解,具有很好的參考價(jià)值,希望對大家有所幫助。一起跟隨小編過來看看吧
    2018-11-11
  • 使用 Python 和 Selenium 解決 Cloudflare 驗(yàn)證碼的問題

    使用 Python 和 Selenium 解決 Cloudflare&

    Cloudflare 驗(yàn)證碼是一種用于區(qū)分人類用戶和自動(dòng)化機(jī)器人的功能,它是 Cloudflare 安全服務(wù)的重要組成部分,旨在防御網(wǎng)站免受自動(dòng)化攻擊和濫用,這篇文章主要介紹了使用 Python 和 Selenium 解決 Cloudflare 驗(yàn)證碼,需要的朋友可以參考下
    2024-06-06
  • Python實(shí)現(xiàn)簡單的用戶交互方法詳解

    Python實(shí)現(xiàn)簡單的用戶交互方法詳解

    這篇文章給大家分享了關(guān)于Python實(shí)現(xiàn)簡單的用戶交互的相關(guān)知識(shí)點(diǎn)內(nèi)容,有需要的朋友們可以學(xué)習(xí)下。
    2018-09-09
  • 輕松實(shí)現(xiàn)python搭建微信公眾平臺(tái)

    輕松實(shí)現(xiàn)python搭建微信公眾平臺(tái)

    這篇文章主要介紹了python搭建微信公眾平臺(tái)的相關(guān)資料和技巧,文中給出了詳細(xì)的python搭建微信公眾平臺(tái)的步驟,感興趣的朋友可以參考一下
    2016-02-02
  • Python Requests庫及用法詳解

    Python Requests庫及用法詳解

    Requests庫作為Python中最受歡迎的HTTP庫之一,為開發(fā)人員提供了簡單而強(qiáng)大的方式來發(fā)送HTTP請求和處理響應(yīng),本文將帶領(lǐng)您深入探索Python Requests庫的世界,我們將從基礎(chǔ)知識(shí)開始,逐步深入,覆蓋各種高級用法和技巧,感興趣的朋友一起看看吧
    2024-06-06
  • pyspark操作hive分區(qū)表及.gz.parquet和part-00000文件壓縮問題

    pyspark操作hive分區(qū)表及.gz.parquet和part-00000文件壓縮問題

    這篇文章主要介紹了pyspark操作hive分區(qū)表及.gz.parquet和part-00000文件壓縮問題,針對問題整理了spark操作hive表的幾種方式,需要的朋友可以參考下
    2021-08-08

最新評論