已知一棵二叉树的前序遍历序列为ABCDEF,中序遍历序列为CBDAEF,请还原这棵二叉树?这棵二叉树的后序遍历结果是多少
时间: 2023-11-23 16:17:06 浏览: 93
已知一棵二叉树的前序遍历序列为ABCDEF,中序遍历序列为CBDAEF,可以还原出如下的二叉树:
```
A
/ \
B E
/ \ \
C D F
```
该二叉树的后序遍历序列为:CDCBFEA。
下面是Python代码实现:
```python
# 定义二叉树节点类
class TreeNode:
def __init__(self, val=0):
self.val = val
self.left = None
self.right = None
# 根据前序遍历序列和中序遍历序列还原二叉树
def buildTree(preorder, inorder):
if not preorder or not inorder:
return None
root_val = preorder[0]
root = TreeNode(root_val)
mid = inorder.index(root_val)
root.left = buildTree(preorder[1:mid+1], inorder[:mid])
root.right = buildTree(preorder[mid+1:], inorder[mid+1:])
return root
# 后序遍历二叉树
def postorderTraversal(root):
if not root:
return []
res = []
stack = [(root, False)]
while stack:
node, visited = stack.pop()
if not node:
continue
if visited:
res.append(node.val)
else:
stack.append((node, True))
stack.append((node.right, False))
stack.append((node.left, False))
return res
# 测试
preorder = ['A', 'B', 'C', 'D', 'E', 'F']
inorder = ['C', 'B', 'D', 'A', 'E', 'F']
root = buildTree(preorder, inorder)
print(postorderTraversal(root)) # ['C', 'D', 'B', 'F', 'E', 'A']
```
阅读全文