leetcode讲解–654. Maximum Binary Tree

654. 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].
递归构造一个二叉树,挺简单的。做这类题,最关键的点在于构造递归的返回条件,没有返回条件或者返回条件不正确,就会无限递归从而导致栈溢出。
java代码
/**
* 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 constructMaximumBinaryTree(nums, 0, nums.length-1);
}

private TreeNode constructMaximumBinaryTree(int[] nums, int begin, int end){
if(begin>end || begin<0 || end<0 || begin>nums.length-1 || end>nums.length-1)
return null;
int maxIndex = maxIndex(nums, begin, end);
TreeNode root = new TreeNode(nums[maxIndex]);
root.left = constructMaximumBinaryTree(nums, begin, maxIndex-1);
root.right = constructMaximumBinaryTree(nums, maxIndex+1, end);
return root;
}

private int maxIndex(int[] nums, int begin, int end){
int max = nums[begin];
int maxIndex = begin;
for(int i=begin;i<=end;i++){
if(max<nums[i]){
max = nums[i];
maxIndex = i;
}
}
return maxIndex;
}
}

评论

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

这个站点使用 Akismet 来减少垃圾评论。了解你的评论数据如何被处理