写在最前面:
接上文,上一篇我讲了如何构造一个二叉树,并且打印出来,这个打印本身是一个层次遍历,就是按一行行输出,今天我们讲一下二叉树的前序遍历、中序遍历、后序遍历
构造和打印二叉树: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