7-2 根据后序和中序遍历输出先序遍历 用python代码
时间: 2023-11-17 22:08:55 浏览: 95
以下是Python代码实现根据后序和中序遍历输出先序遍历的功能:
```
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
def buildTree(inorder, postorder):
if not inorder or not postorder:
return None
root = TreeNode(postorder[-1])
idx = inorder.index(root.val)
root.left = buildTree(inorder[:idx], postorder[:idx])
root.right = buildTree(inorder[idx+1:], postorder[idx:-1])
return root
def preorderTraversal(root):
res = []
if not root:
return res
stack = [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 = [4, 2, 5, 1, 6, 3, 7]
postorder = [4, 5, 2, 6, 7, 3, 1]
root = buildTree(inorder, postorder)
preorder = preorderTraversal(root)
print(preorder)
```
输出结果为:[1, 2, 4, 5, 3, 6, 7]
阅读全文