给定一个不重复的整数数组 nums
。 最大二叉树 可以用下面的算法从 nums
递归地构建:
- 创建一个根节点,其值为
nums
中的最大值。 - 递归地在最大值 左边 的 子数组前缀上 构建左子树。
- 递归地在最大值 右边 的 子数组后缀上 构建右子树。
返回 nums
构建的 最大二叉树 。
方法一:递归
class Solution{
public TreeNode constructMaximumBinaryTreeNode(int[] nums){
return construct(nums, 0, nums.length - 1);
}
public TreeNode construct(int[] nums, int l, int r){
if(l > r) return null;
int max = l;
for(int i = l + 1; i <= r; i++){
if(nums[max] < nums[i]) max = i;
}
TreeNode root = new TreeNode(nums[max]);
root.left = construct(nums, l, max - 1);
root.right = construct(nums, max + 1, r);
return root;
}
}