1.建立二叉树的二叉链表存储结构。 2.实现二叉树的先序、中序和后序三种遍历操作 3. 实现二叉树的先序、中序和后序遍历的非递归操作
时间: 2023-06-20 11:06:43 浏览: 141
二叉树的存储及各种遍历
以下是 Python 代码实现:
```python
# 定义二叉树的二叉链表存储结构
class Node:
def __init__(self, value=None):
self.value = value
self.left_child = None
self.right_child = None
# 定义二叉树类
class BinaryTree:
def __init__(self, root=None):
self.root = root
# 先序遍历(递归)
def preorder_traversal(self, node):
if node is not None:
print(node.value, end=' ')
self.preorder_traversal(node.left_child)
self.preorder_traversal(node.right_child)
# 中序遍历(递归)
def inorder_traversal(self, node):
if node is not None:
self.inorder_traversal(node.left_child)
print(node.value, end=' ')
self.inorder_traversal(node.right_child)
# 后序遍历(递归)
def postorder_traversal(self, node):
if node is not None:
self.postorder_traversal(node.left_child)
self.postorder_traversal(node.right_child)
print(node.value, end=' ')
# 先序遍历(非递归)
def preorder_traversal_non_recursive(self):
node = self.root
stack = []
while node is not None or len(stack) > 0:
while node is not None:
print(node.value, end=' ')
stack.append(node)
node = node.left_child
if len(stack) > 0:
node = stack.pop()
node = node.right_child
# 中序遍历(非递归)
def inorder_traversal_non_recursive(self):
node = self.root
stack = []
while node is not None or len(stack) > 0:
while node is not None:
stack.append(node)
node = node.left_child
if len(stack) > 0:
node = stack.pop()
print(node.value, end=' ')
node = node.right_child
# 后序遍历(非递归)
def postorder_traversal_non_recursive(self):
node = self.root
stack1 = []
stack2 = []
stack1.append(node)
while len(stack1) > 0:
node = stack1.pop()
if node.left_child is not None:
stack1.append(node.left_child)
if node.right_child is not None:
stack1.append(node.right_child)
stack2.append(node)
while len(stack2) > 0:
node = stack2.pop()
print(node.value, end=' ')
```
使用方法:
```python
# 构建二叉树
node1 = Node('A')
node2 = Node('B')
node3 = Node('C')
node4 = Node('D')
node5 = Node('E')
node6 = Node('F')
node7 = Node('G')
node1.left_child = node2
node1.right_child = node3
node2.left_child = node4
node2.right_child = node5
node3.left_child = node6
node3.right_child = node7
binary_tree = BinaryTree(node1)
# 先序遍历(递归)
binary_tree.preorder_traversal(binary_tree.root)
# 中序遍历(递归)
binary_tree.inorder_traversal(binary_tree.root)
# 后序遍历(递归)
binary_tree.postorder_traversal(binary_tree.root)
# 先序遍历(非递归)
binary_tree.preorder_traversal_non_recursive()
# 中序遍历(非递归)
binary_tree.inorder_traversal_non_recursive()
# 后序遍历(非递归)
binary_tree.postorder_traversal_non_recursive()
```
阅读全文