LeetCode:654、最大二叉树

时间:2025-05-15 09:21:39
/** * 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 construct(nums,0,nums.length); } public TreeNode construct(int[] nums,int left,int right){ TreeNode node=new TreeNode(); if (right-left<1)return null;//数组为空,无元素 if(nums.length==1){//只有一个节点 node.val=nums[0]; return node; } int index=left;//数组中最大值的下标 int maxvalue=nums[index];//数组中的最大值 for(int i=left;i<right;i++){//找最大值 if(nums[i]>maxvalue){ maxvalue=nums[i]; index=i; } } node.val=maxvalue;//把最大值添加到节点中 node.left=construct(nums,left,index);//构造左子树 node.right=construct(nums,index+1,right);//构造右子树 return node; } }