根据后序和中序遍历输出先序遍历用oython 解决
时间: 2024-03-18 13:34:53 浏览: 76
根据后序和中序遍历输出先序遍历的Python代码如下:
```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):
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 = [3, 7, 4, 18, 1, 5, 3, 11, 2, 6, 4]
postorder = [3, 4, 7, 1, 3, 5, 2, 4, 6, 11, 18]
root = buildTree(inorder, postorder)
preorder = preorderTraversal(root)
print(preorder)
```
其中,`buildTree`函数用于根据中序遍历和后序遍历构建二叉树,`preorderTraversal`函数用于输出先序遍历。你可以将中序遍历和后序遍历替换成你自己的数据,然后运行代码即可得到先序遍历的结果。
阅读全文