24750: 根据二叉树中后序序列建树
http://cs101.openjudge.cn/practice/24750/
假设二叉树的节点里包含一个大写字母,每个节点的字母都不同。
给定二叉树的中序遍历序列和后序遍历序列(长度均不超过26),请输出该二叉树的前序遍历序列。
输入
2行,均为大写字母组成的字符串,表示一棵二叉树的中序遍历序列与后序遍历排列。
输出
表示二叉树的前序遍历序列。
样例输入
BADC
BDCA样例输出
ABCD来源
Lou Yuke
python
"""
后序遍历的最后一个元素是树的根节点。然后,在中序遍历序列中,根节点将左右子树分开。
可以通过这种方法找到左右子树的中序遍历序列。然后,使用递归地处理左右子树来构建整个树。
"""
def build_tree(inorder, postorder):
if not inorder or not postorder:
return []
root_val = postorder[-1]
root_index = inorder.index(root_val)
left_inorder = inorder[:root_index]
right_inorder = inorder[root_index + 1:]
left_postorder = postorder[:len(left_inorder)]
right_postorder = postorder[len(left_inorder):-1]
root = [root_val]
root.extend(build_tree(left_inorder, left_postorder))
root.extend(build_tree(right_inorder, right_postorder))
return root
def main():
inorder = input().strip()
postorder = input().strip()
preorder = build_tree(inorder, postorder)
print(''.join(preorder))
if __name__ == "__main__":
main()可以利用这幅图,理解下面代码。图源自这里:https://leetcode.cn/problems/construct-binary-tree-from-inorder-and-postorder-traversal/solutions/426738/cong-zhong-xu-yu-hou-xu-bian-li-xu-lie-gou-zao-14/

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_val = postorder.pop()
root = TreeNode(root_val)
# 在中序遍历中找到根节点的位置
root_index = inorder.index(root_val)
# 构建右子树和左子树
root.right = buildTree(inorder[root_index + 1:], postorder)
root.left = buildTree(inorder[:root_index], postorder)
return root
def preorderTraversal(root):
result = []
if root:
result.append(root.val)
result.extend(preorderTraversal(root.left))
result.extend(preorderTraversal(root.right))
return result
# 读取输入
inorder = input().strip()
postorder = input().strip()
# 构建树
root = buildTree(list(inorder), list(postorder))
# 输出前序遍历序列
print(''.join(preorderTraversal(root)))