leetcode讲解–654. Maximum Binary Tree

34次阅读

共计 1374 个字符,预计需要花费 4 分钟才能阅读完成。

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;
}
}

正文完
 0