[leetcode] Maximum Binary Tree
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].
分析:题目分析了一下,要求建立一个满足条件的树,使得根节点是数组里面最大的那个。
建树类型的问题做的比较少,但是建树过程肯定就是找到根节点,然后不停的递归寻找左孩子和又孩子。
在这个题目里,表述比较清晰,左孩子就是左面那个subarrray的最大值,右孩子就是右边那个subarray的最大值。所以比较清晰的知道是用递归的思路。
代码如下:
1 class Solution { 2 public TreeNode constructMaximumBinaryTree(int[] nums) { 3 if ( nums.length == 0 ) return null; 4 return helper(0,nums.length-1,nums); 5 } 6 7 private TreeNode helper(int start, int end, int[] nums) { 8 if ( start > end || start < 0 || end > nums.length - 1 ) return null; 9 int max_index = 0; 10 int max = Integer.MIN_VALUE; 11 for ( int i = start ; i <= end ; i ++ ){ 12 if ( nums[i] > max ){ 13 max = nums[i]; 14 max_index = i; 15 } 16 } 17 TreeNode root = new TreeNode(max); 18 root.left = helper(start,max_index-1,nums); 19 root.right = helper(max_index+1,end,nums); 20 return root; 21 } 22 }
AC:7ms,beats:100%。
这里要注意递归结束条件,其实就是叶子节点的取值要返回null。
拿到题目还是最好手写一些思路和代码,这样思路比较清晰。