新聞中心
1、生成平衡樹的核心是partial_tree方法。

創(chuàng)新互聯(lián)公司專注為客戶提供全方位的互聯(lián)網(wǎng)綜合服務(wù),包含不限于成都網(wǎng)站設(shè)計、成都網(wǎng)站制作、江油網(wǎng)絡(luò)推廣、微信小程序定制開發(fā)、江油網(wǎng)絡(luò)營銷、江油企業(yè)策劃、江油品牌公關(guān)、搜索引擎seo、人物專訪、企業(yè)宣傳片、企業(yè)代運營等,從售前售中售后,我們都將竭誠為您服務(wù),您的肯定,是我們最大的嘉獎;創(chuàng)新互聯(lián)公司為所有大學(xué)生創(chuàng)業(yè)者提供江油建站搭建服務(wù),24小時服務(wù)熱線:18980820575,官方網(wǎng)址:www.cdcxhl.com
它以一個序列和數(shù)字為參數(shù),通過遞歸的方式返回一個序列。其中第一個是結(jié)構(gòu)樹,第二個是不包含在書中的元素。
2、實現(xiàn)的整體思路是,每次傳入的序列分為左半部分、頂點和右半部分,直到不能繼續(xù)拆分,然后逐層返回,最后組合成一棵平衡的二叉樹。
實例
"""
list_to_tree方法將有序列表轉(zhuǎn)化為平衡二叉樹
一棵二叉樹分為樹頂點、左子樹、右子樹,其中左子樹的值都比樹頂節(jié)點小,右子樹的值都比樹頂點大
"""
def make_tree(entry, left, right):
# 創(chuàng)建樹的方法
return (entry, left, right)
def entry(tree):
# 獲取樹的頂點
return tree[0]
def left_branch(tree):
# 獲取左子樹
return tree[1]
def right_branch(tree):
# 獲取右子樹
return tree[2]
def list_to_tree(elements):
return partial_tree(elements, len(elements))[0]
def partial_tree(elts, n):
if n == 0:
return ((), elts)
else:
left_size = (n - 1) 2
left_result = partial_tree(elts, left_size)
left_tree = left_result[0]
non_left_elts = left_result[1]
right_size = n - (left_size + 1)
this_entry = non_left_elts[0]
right_result = partial_tree(non_left_elts[1:], right_size)
right_tree = right_result[0]
remaing_elts = right_result[1]
# print("entry", this_entry)
# print("left_tree", left_tree)
# print("right_tree", right_tree)
return (make_tree(this_entry, left_tree, right_tree), remaing_elts)
if __name__ == "__main__":
tree = list_to_tree((1, 3, 5, 7, 9))
print("生成的平衡二叉樹為:", tree)
print("樹的頂點:", entry(tree))
print("樹的左子樹:", left_branch(tree))
print("樹的右子樹:", right_branch(tree))以上就是python創(chuàng)建平衡二叉樹的方法,希望對大家有所幫助。更多Python學(xué)習(xí)指路:創(chuàng)新互聯(lián)python教程
本文教程操作環(huán)境:windows7系統(tǒng)、Python 3.9.1,DELL G3電腦。
分享題目:創(chuàng)新互聯(lián)Python教程:python創(chuàng)建平衡二叉樹的方法
分享地址:http://www.dlmjj.cn/article/dphcjhg.html


咨詢
建站咨詢
