题目
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].
题目链接
https://leetcode.com/problems/maximum-binary-tree/description/
思路
递归的思想实现:
- Step1:找到数组中最大的值并记录其下标为root_index,对应的值生成root对象;
- Step2:root的左孩子是nums[low,root_index-1];
- Step3:root的右孩子是nums[index+1,high];
- 结束递归的条件是 low > high
code
Java
/* 传入的参数low、high分别表示在本次传入的数组nums可用的元素的最小、最大下标值;
*/
public TreeNode constructTree(int[] nums, int low, int high) {
if (low > high) {//结束递归的条件
return null;
}
int root_index = low;
int maxvalue = nums[low];
for (int i = low + 1; i<= high; i++) {
if (nums[i] > maxvalue) {
maxvalue = nums[i];
root_index = i;
}
}
TreeNode root = new TreeNode(nums[root_index]);
root.left = constructTree(nums, low, root_index-1);
root.right = constructTree(nums, root_index+1, high);
return root;
}
public TreeNode constructMaximumBinaryTree(int[] nums) {
return constructTree(nums, 0, nums.length-1);
}
C++
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
private:
TreeNode* constructTree(vector<int>& nums, int low, int high) {
if (low > high) {//结束递归的条件
return NULL;
}
int root_index = low;
int maxvalue = nums[low];
for (int i = low + 1; i<= high; i++) {
if (nums[i] > maxvalue) {
maxvalue = nums[i];
root_index = i;
}
}
TreeNode* root = new TreeNode(nums[root_index]);
root->left = constructTree(nums, low, root_index-1);
root->right = constructTree(nums, root_index+1, high);
return root;
}
public:
TreeNode* constructMaximumBinaryTree(vector<int>& nums) {
return constructTree(nums, 0, nums.size() - 1);
}
};
python
def constructTree(self, nums, low, high):
if low > high :
return None
root_index = low
maxvalue = nums[low]
for i in range(low,high+1):
if nums[i] > maxvalue :
maxvalue = nums[i];
root_index = i;
root = TreeNode(nums[root_index])
root.left = self.constructTree(nums, low, root_index-1);
root.right = self.constructTree(nums, root_index+1, high);
return root;
def constructMaximumBinaryTree(self, nums):
"""
:type nums: List[int]
:rtype: TreeNode
"""
return self.constructTree(nums, 0, len(nums)-1)