构建最大二叉树的实现流程

流程步骤

erDiagram
    确定根节点 --> 选择最大值作为根节点
    根节点左子树 --> 构建左子树
    根节点右子树 --> 构建右子树

具体步骤及代码

步骤一:选择最大值作为根节点

# 找到列表中的最大值作为根节点
root_val = max(nums)
root = TreeNode(root_val)

步骤二:构建左子树

# 找到最大值所在的索引
root_index = nums.index(root_val)

# 递归构建左子树
root.left = constructMaximumBinaryTree(nums[:root_index])

步骤三:构建右子树

# 递归构建右子树
root.right = constructMaximumBinaryTree(nums[root_index+1:])

完整代码

class TreeNode:
    def __init__(self, val=0, left=None, right=None):
        self.val = val
        self.left = left
        self.right = right

def constructMaximumBinaryTree(nums):
    if not nums:
        return None

    root_val = max(nums)
    root = TreeNode(root_val)

    root_index = nums.index(root_val)

    root.left = constructMaximumBinaryTree(nums[:root_index])
    root.right = constructMaximumBinaryTree(nums[root_index+1:])

    return root

# 测试代码
nums = [3, 2, 1, 6, 0, 5]
root = constructMaximumBinaryTree(nums)

通过以上代码,你可以成功构建一个最大二叉树。希望这篇文章对你有所帮助,加油!如果有任何问题,欢迎随时向我咨询。