BinaryTree:學習二叉樹的Python庫

CharlotteMc 8年前發布 | 11K 次閱讀 二叉樹 Python Python開發

學過二叉樹的朋友都有過這樣的經歷:按照二叉樹的數據手動模擬畫出來二叉樹。但是現在,有了BinaryTree這個庫,你可以不必費這個麻煩了!

BinaryTree是一個小型的Python庫,給你提供了簡單的API,可以依照樹的形式打印一個二叉樹,以及二叉樹的信息概覽。你可以專注于你的算法了!

安裝

通過 Pypi 安裝穩定版:

~$ pip install binarytree

從 Github 安裝最新版本:

~$ git clone https://github.com/joowani/binarytree.git
~$ python binarytree/setup.py install

取決于你環境的不同,可能會需要sudo權限。

入門

默認情況下,二叉樹使用下面的class作為節點:

class Node(object):

    def __init__(self, value):
        self.value = value
        self.left = None
        self.right = None

使用下面的方式以漂亮的形式打印二叉樹:

from binarytree import tree, bst, heap, pprint

# Generate a random binary tree and return its root
my_tree = tree(height=5, balanced=False)

# Generate a random BST and return its root
my_bst = bst(height=5)

# Generate a random max heap and return its root
my_heap = heap(height=3, max=True)

# Pretty print the trees in stdout
pprint(my_tree)
pprint(my_bst)
pprint(my_heap)

也支持 list形式的二叉樹 :

from heapq import heapify
from binarytree import tree, convert, pprint

my_list = [7, 3, 2, 6, 9, 4, 1, 5, 8]

# Convert the list into a tree and return its root
my_tree = convert(my_list)

# Convert the list into a heap and return its root
heapify(my_list)
my_tree = convert(my_list)

# Convert the tree back to a list
my_list = convert(my_tree)

# Pretty-printing also works on lists
pprint(my_list)

快速檢查二叉樹的各個屬性:

from binarytree import tree, inspect

my_tree = tree(height=10)

result = inspect(my_tree)
print(result['height'])
print(result['node_count'])
print(result['leaf_count'])
print(result['min_value'])
print(result['max_value'])
print(result['min_leaf_depth'])
print(result['max_leaf_depth'])
print(result['is_bst'])
print(result['is_max_heap'])
print(result['is_min_heap'])
print(result['is_height_balanced'])
print(result['is_weight_balanced'])

導入Node class然后構建你自己的樹:

from binarytree import Node, pprint

root = Node(1)
root.left = Node(2)
root.right = Node(3)
root.left.left = Node(4)
root.left.right = Node(5)

pprint(root)

如果默認的Node不能滿足你的需要,你可以自定義Node:

from binarytree import Node, setup, tree, pprint

# Define your own null/sentinel value
my_null = -1

# Define your own node class
class MyNode(object):

    def __init__(self, data, left, right):
        self.data = data
        self.l_child = left
        self.r_child = right

# Call setup in the beginning to apply your specification
setup(
    node_init_func=lambda v: MyNode(v, my_null, my_null),
    node_class=MyNode,
    null_value=my_null,
    value_attr='data',
    left_attr='l_child',
    right_attr='r_child'
)
my_custom_tree = tree()
pprint(my_custom_tree)

 

 

來自:http://geek.csdn.net/news/detail/106885

 

 本文由用戶 CharlotteMc 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
 轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
 本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!