Given an integer array with no duplicates. A maximum tree building on this array is defined as follow:
1.The root is the maximum number in the array.
2.The left subtree is the maximum tree constructed from left part subarray divided by the maximum number.
3.The right subtree is the maximum tree constructed from right part subarray divided by the maximum number.
Construct the maximum tree by the given array and output the root node of this tree.
一道简单的递归题,注意递归的过程和结束条件就好了
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public TreeNode constructMaximumBinaryTree(int[] nums) {
return construct(nums,0,nums.length-1);
}
private TreeNode construct (int[] nums,int lo ,int hi){
if(lo>hi)return null;
int max = Integer.MIN_VALUE ;
int pos= lo;
for(int i =lo;i<=hi;i++)
{
if(max<nums[i])
{
max=nums[i];
pos=i;
}
}
TreeNode node = new TreeNode(max);
node.left=construct(nums,lo,pos-1);
node.right=construct(nums,pos+1,hi);
return node;
}
}
网友评论