def mirror_tree(root):
    if not root:
        return
    root.left, root.right = root.right, root.left
    mirror_tree(root.left)
    mirror_tree(root.right)
class TreeNode:
    def __init__(self, x):
        self.val = x
        self.left = None
        self.right = None

def build_tree(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 = build_tree(preorder[1:root_index+1], inorder[:root_index])
    root.right = build_tree(preorder[root_index+1:], inorder[root_index+1:])
    return root
def max_depth(root):
    if not root:
        return 0
    left_depth = max_depth(root.left)
    right_depth = max_depth(root.right)
    return max(left_depth, right_depth) + 1
``
使用PYTHON进行编码:1编写一个函数 mirror_treeroot它接收一个二叉树的根节点 root并将其转换为原始二叉树的镜像。2编写一个函数 build_treepreorder inorder 它接收一棵二叉树的前序遍历和中序遍历结果还原这棵二叉树并返回这棵树的根节点。3编写一个函数 max_depthroot它接收一个二叉树的根节点 root并返回二叉树的最大深度。

原文地址: https://www.cveoy.top/t/topic/cxep 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录