思路:
// @Title: 最大二叉树 (Maximum Binary Tree)
// @Author: qisiii
// @Date: 2024-09-16 00:53:24
// @Runtime: 3 ms
// @Memory: 43.6 MB
// @comment:
// @flag:
/**
* 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) {
if(nums.length<=0){
return null;
}
int index=findMax(nums);
TreeNode root=new TreeNode(nums[index]);
if(nums.length==1){
return root;
}
root.left=constructMaximumBinaryTree(Arrays.copyOfRange(nums,0,index));
root.right=constructMaximumBinaryTree(Arrays.copyOfRange(nums,index+1,nums.length));
return root;
}
private int findMax(int[] nums){
int maxIndex=0;
for(int i=1;i<nums.length;i++){
if(nums[i]>nums[maxIndex]){
maxIndex=i;
}
}
return maxIndex;
}
}