假设一棵二叉树的层次序列为ABCDEFGHIJ,中序序列为DBGEHJACIF,请画出该二叉树,并写出其先序序列和后序序列 Python代码编写
时间: 2023-08-10 11:36:13 浏览: 95
二叉树的先序、中序、后序排列(源代码)
二叉树的结构如下图所示:
```
F
/ \
B G
/ \ \
A D I
/ \ /
C E H
\
J
```
先序序列为:FBADCEGIHJ
后序序列为:AJCHEDIGBF
Python代码实现:
```python
class Node():
def __init__(self, val):
self.val = val
self.left = None
self.right = None
def buildTree(inorder, levelorder):
if not levelorder:
return None
root = Node(levelorder[0])
rootIndex = inorder.index(root.val)
leftInorder = inorder[:rootIndex]
rightInorder = inorder[rootIndex+1:]
leftLevelorder = [n for n in levelorder if n in leftInorder]
rightLevelorder = [n for n in levelorder if n in rightInorder]
root.left = buildTree(leftInorder, leftLevelorder)
root.right = buildTree(rightInorder, rightLevelorder)
return root
inorder = ['D', 'B', 'G', 'E', 'H', 'J', 'A', 'C', 'I', 'F']
levelorder = ['F', 'B', 'G', 'A', 'D', 'I', 'C', 'E', 'H', 'J']
root = buildTree(inorder, levelorder)
def preorder(root):
if not root:
return None
print(root.val, end='')
preorder(root.left)
preorder(root.right)
def postorder(root):
if not root:
return None
postorder(root.left)
postorder(root.right)
print(root.val, end='')
preorder(root) # 输出:FBADCEGIHJ
postorder(root) # 输出:AJCHEDIGBF
```
阅读全文