题目描述:
解题思路:以数组中最大值为中心,分为左右两段,再递归遍历左右两段,注意避免空指针与空数组。
class Solution {
public static TreeNode constructMaximumBinaryTree(int[] nums) {
int [] shuju = new int[2]; //定义数组shuju
shuju = findMaxindex(nums);
if(shuju[0] < 0){
return null;
}
int [] leftNums = new int[shuju[0]];
for(int j=0; j < shuju[0]; j++){
leftNums[j] = nums[j];
}
int [] rightNums = new int[nums.length - shuju[0]-1];
for(int j = 0;j < nums.length - shuju[0]-1 ;j++){
rightNums[j] = nums[shuju[0]+j+1];
}
TreeNode node = new TreeNode(nums[shuju[0]]); //创建节点
node.val = shuju[1]; //将数组最大值赋值给该节点
node.left = constructMaximumBinaryTree(leftNums); //递归创建该节点左子节点
node.right = constructMaximumBinaryTree(rightNums); //递归创建该节点右子节点
return node;
}
public static int[] findMaxindex(int[] nums){ //数组中第一个数为最大值的索引,第二个值为最大值
int [] shuju = new int[2];
int index = -1;
if(nums.length == 0){
shuju[0] = -1;
shuju[1] = -1;
return shuju;
}
else {
int max = nums[0];
for(int i=0; i < nums.length;i++){
if(max <= nums[i]){
max = nums[i];
shuju[0] = i;
shuju[1] = max;
}
}
return shuju;
}
}
public static void midPreOrder(TreeNode node){ //中序遍历
if(node == null){
return ;
}
midPreOrder(node.left);
System.out.println("data is " + node.val);
midPreOrder(node.right);
}
public static void main(String [] args){
int [] Nums = new int[]{3,2,1,6,0,5};
TreeNode newTree = null;
newTree = constructMaximumBinaryTree(Nums); //创建一颗最大二叉树
midPreOrder(newTree);
}
}