Given an integer array with no duplicates. A maximum tree building on this array is defined as follow:
- The root is the maximum number in the array.
- The left subtree is the maximum tree constructed from left part subarray divided by the maximum number.
- 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.
Example 1:
Input: [3,2,1,6,0,5] Output: return the tree root node representing the following tree: 6 / 3 5 / 2 0 1
Note:
- The size of the given array will be in the range [1,1000].
题目含义:给了一堆不重复的数组,然后挑选一个最大的作为root,然后root左边的和右边的有分别按照这个方法进行构建。
1 private TreeNode createTreeNode(int[] nums,int begin,int end) 2 { 3 if (begin>end) return null; 4 int maxValue = Integer.MIN_VALUE; 5 int maxIndex = -1; 6 for (int i=begin;i<=end;i++) 7 { 8 if (nums[i]>maxValue) 9 { 10 maxIndex = i; 11 maxValue = nums[i]; 12 } 13 } 14 if (maxIndex<0) return null; 15 TreeNode node = new TreeNode(nums[maxIndex]); 16 node.left = createTreeNode(nums,begin,maxIndex-1); 17 node.right = createTreeNode(nums,maxIndex+1,end); 18 return node; 19 } 20 21 public TreeNode constructMaximumBinaryTree(int[] nums) { 22 if (nums.length == 0) return null; 23 return createTreeNode(nums,0,nums.length-1); 24 }