您好,登錄后才能下訂單哦!
本篇內(nèi)容主要講解“python怎么創(chuàng)建平衡二叉樹”,感興趣的朋友不妨來看看。本文介紹的方法操作簡單快捷,實(shí)用性強(qiáng)。下面就讓小編來帶大家學(xué)習(xí)“python怎么創(chuàng)建平衡二叉樹”吧!
1、生成平衡樹的核心是partial_tree方法。
它以一個(gè)序列和數(shù)字為參數(shù),通過遞歸的方式返回一個(gè)序列。其中第一個(gè)是結(jié)構(gòu)樹,第二個(gè)是不包含在書中的元素。
2、實(shí)現(xiàn)的整體思路是,每次傳入的序列分為左半部分、頂點(diǎn)和右半部分,直到不能繼續(xù)拆分,然后逐層返回,最后組合成一棵平衡的二叉樹。
實(shí)例
""" list_to_tree方法將有序列表轉(zhuǎn)化為平衡二叉樹 一棵二叉樹分為樹頂點(diǎn)、左子樹、右子樹,其中左子樹的值都比樹頂節(jié)點(diǎn)小,右子樹的值都比樹頂點(diǎn)大 """ def make_tree(entry, left, right): # 創(chuàng)建樹的方法 return (entry, left, right) def entry(tree): # 獲取樹的頂點(diǎn) 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("樹的頂點(diǎn):", entry(tree)) print("樹的左子樹:", left_branch(tree)) print("樹的右子樹:", right_branch(tree))
到此,相信大家對“python怎么創(chuàng)建平衡二叉樹”有了更深的了解,不妨來實(shí)際操作一番吧!這里是億速云網(wǎng)站,更多相關(guān)內(nèi)容可以進(jìn)入相關(guān)頻道進(jìn)行查詢,關(guān)注我們,繼續(xù)學(xué)習(xí)!
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。