每次找到数组中的最大值,然后递归的构建左右树
public TreeNode constructMaximumBinaryTree(int[] nums) { if (nums.length==0) return null; return builder(nums,0,nums.length-1); } public TreeNode builder(int[] nums,int sta,int end) { /* 思路就是每次找到最大值,然后分为两个子数组递归构建左右树 */ if (sta>end) return null; int max = Integer.MIN_VALUE; int index = -1; for (int i = sta; i <= end ; i++) { if (nums[i]>max) { max = nums[i]; index = i; } } TreeNode root = new TreeNode(max); root.left = builder(nums,sta,index-1); root.right = builder(nums,index+1,end); return root; }