给定一个不重复的数组,其最大值树的定义如下:
1.树根是数组中的最大值。
2.左树也是颗最大值树,是从最大值分裂开的左半部分的数组所构造出来的。
3.右树也是颗最大值树,是从最大值分裂开的右半部分的数组所构造出来的。
通过给定数组构造出它的最大值树吧少年。
英语原文:
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.
例子 1:
输入: [3,2,1,6,0,5] 输出: 返回下面的树根节点: 6 / \ 3 5 \ / 2 0 \ 1
解答:
递归解决
/**
* 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 {
public:
TreeNode* constructMaximumBinaryTree(vector<int>& nums) {
return makeMaxTree(nums, 0, nums.size()-1);
}
TreeNode* makeMaxTree(vector<int>& nums, int startIndex, int endIndex)
{
auto maxIt = max_element(nums.begin() + startIndex, nums.begin() + endIndex + 1);
TreeNode* newTree = new TreeNode(*maxIt);
int maxPos = maxIt - nums.begin();
if (maxPos > 0 && maxPos > startIndex)
newTree->left = makeMaxTree(nums, startIndex, maxPos - 1);
if (maxPos < endIndex)
newTree->right = makeMaxTree(nums, maxPos + 1, endIndex);
return newTree;
}
};