根据后序和中序遍历输出先序遍历python
时间: 2023-06-05 10:47:21 浏览: 180
以下是Python代码实现:
```python
def build_tree(inorder, postorder):
if not inorder:
return None
root_val = postorder.pop()
root = TreeNode(root_val)
index = inorder.index(root_val)
root.right = build_tree(inorder[index+1:], postorder)
root.left = build_tree(inorder[:index], postorder)
return root
def preorder_traversal(root):
if not root:
return []
stack, res = [root], []
while stack:
node = stack.pop()
res.append(node.val)
if node.right:
stack.append(node.right)
if node.left:
stack.append(node.left)
return res
inorder = [9, 3, 15, 20, 7]
postorder = [9, 15, 7, 20, 3]
root = build_tree(inorder, postorder)
preorder = preorder_traversal(root)
print(preorder)
```
输出结果为:[3, 9, 20, 15, 7]
阅读全文