开始之前先给自己打个鸡血吧:
A journey of a thousand miles begins with a single step. 千里之行始于足下。
题源:https://leetcode.cn/problems/maximum-binary-tree/
题目详情:
给定一个不重复的整数数组 nums 。 最大二叉树 可以用下面的算法从 nums 递归地构建:
创建一个根节点,其值为 nums 中的最大值。
递归地在最大值 左边 的 子数组前缀上 构建左子树。
递归地在最大值 右边 的 子数组后缀上 构建右子树。
返回 nums 构建的 最大二叉树 。
思路
递归实现
代码
python
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution(object):
def constructMaximumBinaryTree(self, nums):
"""
:type nums: List[int]
:rtype: TreeNode
"""
if not nums:
return
root=TreeNode(max(nums))
index=nums.index(max(nums))
root.left=self.constructMaximumBinaryTree(nums[0:index])
root.right=self.constructMaximumBinaryTree(nums[index+1:])
return root