根据前序遍历和后序遍历得到中序遍历 Python
时间: 2023-12-10 12:33:55 浏览: 70
Python实现输入二叉树的先序和中序遍历,再输出后序遍历操作示例
5星 · 资源好评率100%
根据前序遍历和后序遍历得到中序遍历的方法如下:
```python
def getInorder(preorder, inorder, postorder):
if len(preorder) == 0:
return []
if len(preorder) == 1:
return [preorder[0]]
root = postorder[-1]
rootIndex = inorder.index(root)
leftInorder = inorder[:rootIndex]
rightInorder = inorder[rootIndex+1:]
leftPreorder = preorder[1:1+len(leftInorder)]
rightPreorder = preorder[1+len(leftInorder):]
leftPostorder = postorder[:len(leftInorder)]
rightPostorder = postorder[len(leftInorder):-1]
left = getInorder(leftPreorder, leftInorder, leftPostorder)
right = getInorder(rightPreorder, rightInorder, rightPostorder)
return left + [root] + right
```
其中,preorder表示前序遍历结果,inorder表示中序遍历结果,postorder表示后序遍历结果。函数的返回值为中序遍历结果。
阅读全文