class Node:
'''定义结点'''
def __init__(self, val):
self.val = val
self.left = None
self.right = None
class Tree:
def __init__(self):
self.root = None
def add(self, item):
'''层次添加元素'''
node = Node(item)
if self.root is None:
self.root = node
return
queue = [self.root]
while queue:
cur_node = queue.pop(0)
if cur_node.left is None:
cur_node.left = node
return
else:
queue.append(cur_node.left)
if cur_node.right is None:
cur_node.right = node
return
else:
queue.append(cur_node.right)
def preorder(self, root):
'''前序遍历,堆栈,迭代'''
if not root:
return
stack = []
node = root
while stack or node:
while node:
print(node.val, end=' ')
stack.append(node)
node = node.left
node = stack.pop()
node = node.right
print()
def inorder(self, root):
'''中序遍历,堆栈,迭代'''
if not root:
return
stack = []
node = root
while stack or node:
while node:
stack.append(node)
node = node.left
node = stack.pop()
print(node.val, end=' ')
node = node.right
print()
def postorder(self, root):
'''后续遍历,堆栈,迭代'''
if root == None:
return
stack = []
res = []
node = root
stack.append(node)
while stack:
node = stack.pop()
if node.left:
stack.append(node.left)
if node.right:
stack.append(node.right)
res.append(node)
while res:
print(res.pop().val, end=' ')
print()
def breadth_travel(self, root):
'''层次遍历'''
queue = [root]
while queue:
cur_node = queue.pop(0)
print(cur_node.val, end=' ')
if cur_node.left is not None:
queue.append(cur_node.left)
if cur_node.right is not None:
queue.append(cur_node.right)
print()
if __name__ == '__main__':
tree = Tree()
for i in range(10):
tree.add(i)
print('前序遍历:', end='')
tree.preorder(tree.root)
print('中序遍历:', end='')
tree.inorder(tree.root)
print('后序遍历:', end='')
tree.postorder(tree.root)
print('层次遍历:', end='')
tree.breadth_travel(tree.root)
构建一个如下图所示的二叉树:
遍历结果如下: