python二叉树的前序遍历、中序遍历、后序遍历

写在最前面:

接上文,上一篇我讲了如何构造一个二叉树,并且打印出来,这个打印本身是一个层次遍历,就是按一行行输出,今天我们讲一下二叉树的前序遍历、中序遍历、后序遍历

构造和打印二叉树:https://blog.csdn.net/ssjdoudou/article/details/83692895

 

'''
树的构建:
     3
  9     20
     15    7
'''

class Tree():
    '树的构造'
    def __init__(self,data, left = 0, right = 0):
        self.data = data
        self.left = left
        self.right = right


    def __str__(self):
        return str(self.data)


class MyTree():
    '二叉树的实现'
    def __init__(self,base = 0):
        self.base = base

    def _Empty(self):
        '判断是否为空树'
        if self.base == 0:
            return True
        else:
            return False

    def front_search(self,tree_base):
        '前序遍历:根-左-右'
        if tree_base == 0:
            return
        print(tree_base.data)
        self.front_search(tree_base.left)
        self.front_search(tree_base.right)

    def middle_search(self,tree_base):
        '中序遍历:左-根-右'
        if tree_base == 0:
            return
        self.middle_search(tree_base.left)
        print(tree_base.data)
        self.middle_search(tree_base.right)

    def behind_search(self,tree_base):
        '后序遍历:左-右-根'
        if tree_base == 0:
            return
        self.behind_search(tree_base.left)
        self.behind_search(tree_base.right)
        print(tree_base.data)
# test tree


tree1 = Tree(data=15)
tree2 = Tree(data=7)
tree3 = Tree(20,tree1,tree2)
tree4 = Tree(data=9)
base = Tree(3,tree4,tree3)
btree = MyTree(base)
print('前序遍历:')
btree.front_search(btree.base)
print('中序遍历:')
btree.middle_search(btree.base)
print('后序遍历:')
btree.behind_search(btree.base)

也可以这么写:

tree1 = Tree(data=15)
tree2 = Tree(data=7)
tree3 = Tree(20,tree1,tree2)
tree4 = Tree(data=9)
base = Tree(3,tree4,tree3)
print('前序遍历:')
MyTree(base).front_search(base)
print('中序遍历:')
MyTree(base).front_search(base)
print('后序遍历:')
MyTree(base).behind_search(base)

还还可以这么写:

tree1 = Tree(data=15)
tree2 = Tree(data=7)
tree3 = Tree(20,tree1,tree2)
tree4 = Tree(data=9)
base = Tree(3,tree4,tree3)
btree = MyTree()
print('前序遍历:')
btree.front_search(base)
print('中序遍历:')
btree.middle_search(base)
print('后序遍历:')
btree.behind_search(base)

这些写法都是类的灵活调用,大家自己领悟吧... 

 

输出:

前序遍历:
3
9
20
15
7
中序遍历:
9
3
15
20
7
后序遍历:
9
15
7
20
3

Process finished with exit code 0

 

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值