654. 最大二叉树
中等
592
相关企业
给定一个不重复的整数数组 nums
。 最大二叉树 可以用下面的算法从 nums
递归地构建:
- 创建一个根节点,其值为
nums
中的最大值。 - 递归地在最大值 左边 的 子数组前缀上 构建左子树。
- 递归地在最大值 右边 的 子数组后缀上 构建右子树。
返回 nums
构建的 最大二叉树 。
示例 1:
输入:nums = [3,2,1,6,0,5] 输出:[6,3,5,null,2,0,null,null,1] 解释:递归调用如下所示: - [3,2,1,6,0,5] 中的最大值是 6 ,左边部分是 [3,2,1] ,右边部分是 [0,5] 。 - [3,2,1] 中的最大值是 3 ,左边部分是 [] ,右边部分是 [2,1] 。 - 空数组,无子节点。 - [2,1] 中的最大值是 2 ,左边部分是 [] ,右边部分是 [1] 。 - 空数组,无子节点。 - 只有一个元素,所以子节点是一个值为 1 的节点。 - [0,5] 中的最大值是 5 ,左边部分是 [0] ,右边部分是 [] 。 - 只有一个元素,所以子节点是一个值为 0 的节点。 - 空数组,无子节点。
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
public TreeNode constructMaximumBinaryTree(int[] nums) {
return constructMaximumBinaryTree2(nums,0,nums.length);
}
public TreeNode constructMaximumBinaryTree2(int[] nums, int left, int right){
if(right-left<1){
return null; //没有元素返回空集
}
if(right-left==1){
return new TreeNode(nums[left]); //只有一个元素,只有一个根节点
}
int maxIndex = left; //从第一个开始历遍,找到最大值
int maxValue = nums[maxIndex];
for(int i =left+1; i<right;i++){
if(nums[i]>maxValue){
maxValue = nums[i];
maxIndex =i;
}
}
TreeNode root = new TreeNode(maxValue); //以最大值为中节点
root.left = constructMaximumBinaryTree2(nums,left,maxIndex);
root.right=constructMaximumBinaryTree2(nums,maxIndex+1,right);
return root;
}
}
小结:
1.构造二叉树,才用前序历遍
2.注意这道题,构造的两个函数方法,可以避免构造新的数组来储存划分后的数组
3.初始值int left =0, int right = nums.length
4.return root, 细品迭代