菜鸡1号


私信TA

用户名:uq_69651989863

访问量:890

签 名:

等  级
排  名 1293
经  验 2914
参赛次数 0
文章发表 48
年  龄 0
在职情况 学生
学  校
专  业

  自我简介:

TA的其他文章

解题思路:

注意事项:

参考代码:

# 定义树节点的数据结构

class TreeNode:

    def __init__(self, val):

        self.val = val

        self.left = None

        self.right = None


# 根据先序遍历和中序遍历构建二叉树

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 []

    

    result = []

    result.extend(postorderTraversal(root.left))

    result.extend(postorderTraversal(root.right))

    result.append(root.val)

    

    return result


# 主函数

def main():

    preorder = input().strip()  # 先序遍历序列

    inorder = input().strip()  # 中序遍历序列

    

    # 构建二叉树

    root = buildTree(preorder, inorder)

    

    # 后序遍历二叉树

    result = postorderTraversal(root)

    

    # 输出后序遍历序列

    print(''.join(result))


# 调用主函数

main()


 

0.0分

0 人评分

看不懂代码?想转换其他语言的代码? 或者想问其他问题? 试试问问AI编程助手,随时响应你的问题:

编程语言转换

万能编程问答  

代码解释器

代码纠错

SQL生成与解释

  评论区