python基础(五)——二叉树的实现

class Node(object):
    def __init__(self, index):
        self.index = index
        self.left_child = None
        self.right_child = None
class BinarySearchTree(object):
    def __init__(self, root):
        self.root = root
    #前序遍历,根左右
    def pre_travel(self, node):
        if not node:
            return
        print(node.index)
        self.pre_travel(node.left_child)
        self.pre_travel(node.right_child)
    #后序遍历,左右根
    def post_travel(self, node):
        if not node:
            return
        self.post_travel(node.left_child)
        self.post_travel(node.right_child)
        print(node.index)
    #中序遍历,左根右
    def in_travel(self, node):
        if not node:
            return
        self.in_travel(node.left_child)
        print(node.index)
        self.in_travel(node.right_child)
node_dict = {}
for i in range(1, 11):
    node_dict[i] = Node(i)
node_dict[1].left_child = node_dict[2]
node_dict[1].right_child = node_dict[3]
node_dict[2].left_child = node_dict[4]
node_dict[2].right_child = node_dict[5]
node_dict[3].left_child = node_dict[6]
node_dict[3].right_child = node_dict[7]
node_dict[4].left_child = node_dict[8]
node_dict[4].right_child = node_dict[9]
node_dict[5].left_child = node_dict[10]
tree = BinarySearchTree(node_dict[1])
print("\npre order travel:")
tree.pre_travel(tree.root)
print("\npost order travel:")
tree.post_travel(tree.root)
print("\nin order travel:")
tree.in_travel(tree.root)

生成的二叉树如下:
二叉树


输出结果:

pre order travel:
1
2
4
8
9
5
10
3
6
7

post order travel:
8
9
4
10
5
2
6
7
3
1

in order travel:
8
4
9
2
10
5
1
6
3
7
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值