已知一个二叉树的前序遍历和中序遍历 求后序遍历
时间: 2023-12-14 22:33:42 浏览: 156
根据二叉树的前序遍历和中序遍历可以唯一确定一棵二叉树,因此可以通过这两个遍历序列构建出这棵二叉树,然后再进行后序遍历。
具体步骤如下:
1. 根据前序遍历序列确定根节点,假设为root。
2. 在中序遍历序列中找到根节点root的位置,将中序遍历序列分为左子树和右子树两部分,分别对左右子树递归进行步骤1和步骤2,直到序列为空或者只有一个节点。
3. 对于每个节点,先遍历它的左子树,再遍历它的右子树,最后遍历它本身,即可得到后序遍历序列。
下面是Python代码实现:
```python
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
def buildTree(preorder, inorder):
if not preorder or not inorder:
return None
root_val = preorder[0]
root = TreeNode(root_val)
root_index = inorder.index(root_val)
root.left = buildTree(preorder[1:root_index+1], inorder[:root_index])
root.right = buildTree(preorder[root_index+1:], inorder[root_index+1:])
return root
def postorderTraversal(root):
if not root:
return []
stack = [root]
res = []
while stack:
node = stack.pop()
res.append(node.val)
if node.left:
stack.append(node.left)
if node.right:
stack.append(node.right)
return res[::-1]
preorder = [1, 2, 4, 5, 3, 6, 7]
inorder = [4, 2, 5, 1, 6, 3, 7]
root = buildTree(preorder, inorder)
postorder = postorderTraversal(root)
print(postorder) # 输出:[4, 5, 2, 6, 7, 3, 1]
```
阅读全文
相关推荐
















