原题链接:https://leetcode.com/problems/maximum-binary-tree/
1. 题目介绍
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.
给出一个没有重复数字的整数数组。在这个数组的基础上,建立一个最大的树。
最大的树的定义是:
根节点是数组中最大的数字。
数组中最大的数字将数组一分为二,根节点的左子树是左半部分数组的最大的树,根节点的右子树是右半部分数组最大的树。
根据给出的数组构建一棵最大的树,并且返回这棵树的根节点。
2. 解题思路
本题是典型的递归求解问题。
对于每一步的计算,都是类似的。
设置一个递归函数,函数的功能就是从求解数组下标范围在start到end之间的最大的树。
首先,需要找到数组中最大的数在哪里,比如根节点的下标是index,找到后将根节点设为最大的数。
根节点的左子树,可以用递归函数求start到index-1范围内的最大的树,
根节点的右子树,可以用递归函数求index+1到end范围内的最大的树。
最后返回根节点即可。
实现代码
/**
* 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 helper(0,nums.length-1,nums);
}
public TreeNode helper(int start, int end, int[] nums){
if(start > end ){
return null;
}
int max = 0;
int max_index = start;
for(int i = start ; i <=end ; i++){
if(nums[i] > max){
max = nums[i];
max_index = i;
}
}
TreeNode root = new TreeNode(nums[max_index]);
root.left = helper(start, max_index-1,nums);
root.right = helper(max_index+1 , end, nums);
return root;
}
}