返回 登录
0

BinaryTree:学习二叉树的Python库

原文Python Library for Learning Binary Trees
作者:joohwan 翻译赖信涛 责编:仲培艺

学过二叉树的朋友都有过这样的经历:按照二叉树的数据手动模拟画出来二叉树。但是现在,有了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)

讨论

andydoan说: 也可以关注一下这些图表打印的库:


2016年11月18日-20日,由CSDN重磅打造的年终技术盛会SDCC 2016中国软件开发者大会将在北京举行,大会秉承干货实料(案例)的内容原则,本次大会共设置了12大专题、近百位的演讲嘉宾,并邀请业内顶尖的CTO、架构师和技术专家,与参会嘉宾共同探讨电商架构、高可用架构、编程语言、架构师进阶、微信开发、前端、平台架构演进、基于Spark的大数据系统设计、自动化运维与容器实践、高吞吐数据库系统设计要领、移动视频直播技术等。10月14日仍是五折抢票,最低1400元,注册参会

评论