日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問(wèn) 生活随笔!

生活随笔

當(dāng)前位置: 首頁(yè) > 编程语言 > python >内容正文

python

数据结构之二叉树:二叉查找树的先序、中序、后序、层序遍历,Python代码实现——10(续)

發(fā)布時(shí)間:2024/7/5 python 43 豆豆
生活随笔 收集整理的這篇文章主要介紹了 数据结构之二叉树:二叉查找树的先序、中序、后序、层序遍历,Python代码实现——10(续) 小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.

數(shù)據(jù)結(jié)構(gòu)之二叉查找樹(shù)的代碼實(shí)現(xiàn)

本節(jié)繼續(xù)對(duì)上一節(jié)BST的功能實(shí)現(xiàn)
在實(shí)現(xiàn)之前,先對(duì)要實(shí)現(xiàn)的功能進(jìn)行一下簡(jiǎn)單的介紹

BST的幾種常見(jiàn)遍歷方式

以一個(gè)簡(jiǎn)化的樹(shù)為例,一棵樹(shù)包含根(父)結(jié)點(diǎn)和其左子樹(shù)及右子樹(shù):

遍歷順序的先后是指根(父)結(jié)點(diǎn)被遍歷的相對(duì)順序

  • 先序遍歷:指的是“先根后左再右”
  • 中序遍歷:指的是“先左后根再右”
  • 后序遍歷:指的是“先左后又再根”
  • 如果子樹(shù)也存在子樹(shù),則也需按此規(guī)則進(jìn)行遍歷,一般是遞歸地進(jìn)行遍歷

    4. 層序遍歷:指按樹(shù)層次順序,從根結(jié)點(diǎn)往下,子結(jié)點(diǎn)從左到右地遍歷


    5. 獲取樹(shù)的最大深度

    • 實(shí)現(xiàn)步驟(使用遞歸):
      1.如果根結(jié)點(diǎn)為空,則最大深度為0 ;
      2.計(jì)算左子樹(shù)的最大深度;
      3.計(jì)算右子樹(shù)的最大深度;
      4.當(dāng)前樹(shù)的最大深度=左子樹(shù)的最大深度和右子樹(shù)的最大深度中的較大者+1

    接下來(lái)對(duì)BST的這些遍歷功能進(jìn)行實(shí)現(xiàn)

    實(shí)現(xiàn)功能

  • pre_ergodic()實(shí)現(xiàn)BST的先序遍歷,返回遍歷的元素組成的列表
  • mid_ergodic()實(shí)現(xiàn)BST的中序遍歷,返回遍歷的元素組成的列表
  • post_ergodic()實(shí)現(xiàn)BST的后序遍歷,返回遍歷的元素組成的列表
  • layer_ergodic()實(shí)現(xiàn)BST的層序遍歷,返回遍歷的元素組成的列表
  • max_depth()獲取樹(shù)的最大深度
  • Python代碼實(shí)現(xiàn)

    注:注釋的測(cè)試代碼是前一節(jié)的實(shí)現(xiàn),可以忽略

    import operatorclass Node:def __init__(self, key=None, value=None):self.key = keyself.value = valueself.left = Noneself.right = Noneclass BinarySearchTree:def __init__(self):self.root = Noneself.len = 0def size(self):return self.lendef put(self, _key, _value):"""Put an element into this tree and generate a new BST"""def put_into(node, _key, _value):"""Adjust position of new inserted nodeby BST character:left > root > right"""if not node:self.len += 1return Node(_key, _value)if operator.lt(_key, node.key):node.left = put_into(node.left, _key, _value)elif operator.gt(_key, node.key):node.right = put_into(node.right, _key, _value)elif operator.eq(_key, node.key):node.value = _valuereturn nodeself.root = put_into(self.root, _key, _value)return self.rootdef get(self, _key):"""Get a value responding to the given _key from this tree"""def get_value_by_key(node, _key):if not node:returnif operator.lt(_key, node.key):return get_value_by_key(node.left, _key)elif operator.gt(_key, node.key):return get_value_by_key(node.right, _key)else:return node.valuereturn get_value_by_key(self.root, _key)## def delete(self, _key):# """Delete a node responding to the giving key(_key)"""# def delete_value_by_key(node, _key):# if not node:# return# if operator.lt(_key, node.key):# node.left = delete_value_by_key(node.left, _key)# elif operator.gt(_key, node.key):# node.right = delete_value_by_key(node.right, _key)# else:# self.len -= 1# to_delete_node = node# if node == self.root:# self.root = None# return# # node = None# if not to_delete_node.left:# return to_delete_node.right# elif not to_delete_node.right:# return to_delete_node.left# else:# min_right_tree = to_delete_node.right# pre = min_right_tree# while min_right_tree.left:# pre = min_right_tree# min_right_tree = min_right_tree.left# pre.left = None# min_right_tree.left = to_delete_node.left# min_right_tree.right = to_delete_node.right# return min_right_tree# return delete_value_by_key(self.root, _key)## def min_key(self):# """Find the minimum key"""# def min_node(node):# while node.left:# node = node.left# return node# return min_node(self.root).key## def max_key(self):# """Find the maximum key"""# def max_node(node):# while node.right:# node = node.right# return node# return max_node(self.root).keydef pre_ergodic(self):"""Get every key of this tree, pre_ergodic; Return a list of its keys"""def pre_ergodic(node, keys_list):"""Root --> Left --> Right"""if not node:returnkeys_list.append(node.key)if node.left:pre_ergodic(node.left, keys_list)if node.right:pre_ergodic(node.right, keys_list)keys_list = []pre_ergodic(self.root, keys_list)return keys_listdef mid_ergodic(self):def mid_ergodic(node, keys_list):"""Left --> Root --> Right"""if not node:returnif node.left:mid_ergodic(node.left, keys_list)keys_list.append(node.key)if node.right:mid_ergodic(node.right, keys_list)keys_list = []mid_ergodic(self.root, keys_list)return keys_listdef post_ergodic(self):def post_ergodic(node, keys_list):"""Left --> Right --> Root"""if not node:returnif node.left:post_ergodic(node.left, keys_list)if node.right:post_ergodic(node.right, keys_list)keys_list.append(node.key)keys_list = []post_ergodic(self.root, keys_list)return keys_listdef layer_ergodic(self):"""Root-->Left --> Right"""queue = [self.root]keys = []while queue:node = queue.pop(0)keys.append(node.key)if node.left:queue.append(node.left)if node.right: queue.append(node.right)return keysdef max_depth(self):"""Get the max depth of this tree"""def max_depth(node):max_left, max_right = 0, 0if not node:return 0if node.left:max_left = max_depth(node.left)if node.right:max_right = max_depth(node.right)return max(max_left, max_right) + 1return max_depth(self.root)

    代碼測(cè)試

    if __name__ == '__main__':BST = BinarySearchTree()BST.put('e', '5')BST.put('b', '2')BST.put('g', '7')BST.put('a', '1')BST.put('d', '4')BST.put('f', '6')BST.put('h', '8')BST.put('c', '3')print(f"The size of this binary tree now is {BST.size()}\n")print("pre_order:\n", [(key, BST.get(key)) for key in BST.pre_ergodic()])print("mid_order:\n", [(key, BST.get(key)) for key in BST.mid_ergodic()])print("post_order:\n", [(key, BST.get(key)) for key in BST.post_ergodic()])print("layer_order:\n", [(key, BST.get(key)) for key in BST.layer_ergodic()])print(f"Get the maximum depth of this tree: {BST.max_depth()}")

    測(cè)試結(jié)果

    The size of this binary tree now is 8pre_order:[('e', '5'), ('b', '2'), ('a', '1'), ('d', '4'), ('c', '3'), ('g', '7'), ('f', '6'), ('h', '8')] mid_order:[('a', '1'), ('b', '2'), ('c', '3'), ('d', '4'), ('e', '5'), ('f', '6'), ('g', '7'), ('h', '8')] post_order:[('a', '1'), ('c', '3'), ('d', '4'), ('b', '2'), ('f', '6'), ('h', '8'), ('g', '7'), ('e', '5')] layer_order:[('e', '5'), ('b', '2'), ('g', '7'), ('a', '1'), ('d', '4'), ('f', '6'), ('h', '8'), ('c', '3')] Get the maximum depth of this tree: 4Process finished with exit code 0


    根據(jù)前/后序+中序確定這顆二叉查找樹(shù):

    最大深度顯然是4

    總結(jié)

    以上是生活随笔為你收集整理的数据结构之二叉树:二叉查找树的先序、中序、后序、层序遍历,Python代码实现——10(续)的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。

    如果覺(jué)得生活随笔網(wǎng)站內(nèi)容還不錯(cuò),歡迎將生活随笔推薦給好友。