编写一个abcdefghij二叉树的程序,并分别按照前序遍历二叉树次序、中序遍历二叉树次序和后序遍历二叉树次序输出显示二叉树各结点的信息。
时间: 2023-12-10 20:33:29 浏览: 83
实现先序,中序和后序遍历的二叉树遍历程序
5星 · 资源好评率100%
以下是按照前序遍历、中序遍历和后序遍历分别输出二叉树结点信息的Python程序:
```python
# 定义二叉树结点类
class TreeNode:
def __init__(self, val):
self.val = val
self.left = None
self.right = None
# 构建二叉树
def buildTree():
# 构建结点
A = TreeNode('A')
B = TreeNode('B')
C = TreeNode('C')
D = TreeNode('D')
E = TreeNode('E')
F = TreeNode('F')
G = TreeNode('G')
H = TreeNode('H')
I = TreeNode('I')
J = TreeNode('J')
# 构建结点之间的关系
A.left = B
A.right = C
B.left = D
B.right = E
C.left = F
C.right = G
E.left = H
E.right = I
G.right = J
# 返回根结点
return A
# 前序遍历
def preOrder(root):
if not root:
return
print(root.val, end=' ')
preOrder(root.left)
preOrder(root.right)
# 中序遍历
def inOrder(root):
if not root:
return
inOrder(root.left)
print(root.val, end=' ')
inOrder(root.right)
# 后序遍历
def postOrder(root):
if not root:
return
postOrder(root.left)
postOrder(root.right)
print(root.val, end=' ')
# 构建二叉树
root = buildTree()
# 前序遍历输出
print('前序遍历:', end='')
preOrder(root)
print()
# 中序遍历输出
print('中序遍历:', end='')
inOrder(root)
print()
# 后序遍历输出
print('后序遍历:', end='')
postOrder(root)
print()
```
阅读全文