python 二叉树

定义:

class BTree(object):
    def __init__(self, value):
        self.l_child = None
        self.r_child = None
        self.value = value
    def insert_left(self, value):
        bt_node = BTree(value)
        bt_node.l_child = self.l_child
        self.l_child = bt_node
    def insert_right(self, value):
        bt_node = BTree(value)
        bt_node.r_child = self.r_child
        self.r_child = bt_node

def in_order(node, return_list):
    if node:
        in_order(node.l_child, return_list)
        return_list.append(node.value)
        in_order(node.r_child, return_list)
        return return_list

插入节点

n0 = BTree(0)
n0.insert_left(1)
n0.insert_right(2)
n0.l_child.insert_left(3)
n0.l_child.insert_right(4)
n0.r_child.insert_left(5)
n0.r_child.insert_right(6)

树为:

            0
    1                2
3        4        5        6

调用中序遍历

>>> in_order(n0,[])
[3, 1, 4, 0, 5, 2, 6]

前序遍历

def pre_order(node, return_list):
	if node:
		return_list.append(node.value)
		pre_order(node.l_child, return_list)
		pre_order(node.r_child, return_list)
		return return_list

>>> pre_order(n0,[])
[0, 1, 3, 4, 2, 5, 6]

后序遍历

def post_order(node, return_list):
    if node:
        post_order(node.l_child, return_list)
        post_order(node.r_child, return_list)
        return_list.append(node.value)
        return return_list

>>> post_order(n0,[])
[3, 4, 1, 5, 6, 2, 0]

posted on 2016-11-14 16:10  kramer  阅读(164)  评论(0编辑  收藏  举报

导航