一、题目
二、代码
/**
* 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 make_tree(int[] nums)
{
// System.out.println("分割");
int i;
int length = nums.length;
if(length<=0) return null;
int max = 0;
int max_index = 0;
for(i=0; i<length; i++)
{
if(nums[i]>max)
{
max = nums[i];
max_index = i;
}
// System.out.println(" "+nums[i]);
}
// System.out.println("length "+length);
// System.out.println("max_index "+max_index);
// System.out.println("切割点 "+nums[max_index]);
// print("length "+length);
// print("length "+length);
int[] left_array = new int[max_index];
int[] right_array = new int[length-max_index-1];
for(i=0;i<max_index;i++)
{
left_array[i] = nums[i];
}
for(i=max_index+1;i<length;i++)
{
right_array[i-(max_index+1)] = nums[i];
}
TreeNode root = new TreeNode(max);
root.left = make_tree(left_array);
root.right = make_tree(right_array);
return root;
}
public TreeNode constructMaximumBinaryTree(int[] nums)
{
if(nums.length==0) return null;
return make_tree(nums);
}
}
三、运行结果
四、附录
二刷
/**
* 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 max = -1;
int max_index = -1;
int i;
int length = nums.length;
//找到最大数值和下标
for(i=0;i<length;i++)
{
if(nums[i]>max)
{
max = nums[i];
max_index = i;
}
}
int[] left = new int[max_index];
int[] right = new int[length-1-max_index];
for(i=0;i<max_index;i++) left[i] = nums[i];
for(i=max_index+1;i<length;i++) right[i-max_index-1] = nums[i];
TreeNode root = new TreeNode(max);
root.left = constructMaximumBinaryTree(left);
root.right = constructMaximumBinaryTree(right);
return root;
}
}