/**
* 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) {
TreeNode *root = new TreeNode(0);
getNode(root, nums, 0, nums.size() - 1);
return root;
}
private:
void getNode(TreeNode *root, vector<int>& nums, int low, int high)
{
if (low > high)
{
root = NULL;
return;
}
else if (low == high)
{
root->val = nums[high];
return;
}
int maxNum = nums[low];
int res = low;
for (int i = low; i <= high; i++)
{
if (nums[i] > maxNum)
{
maxNum = nums[i];
res = i;
}
}
root->val = nums[res];
if (low <= res - 1)
{
getNode(root->left = new TreeNode(0), nums, low, res - 1);
}
if (res + 1 <= high)
{
getNode(root->right = new TreeNode(0), nums, res + 1, high);
}
}
};