遞歸求解,每次找出最的的元素作爲樹根,思路有點類似快排
class Solution {
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
public:
TreeNode* sub_construct(vector<int>& nums , int start,int end){
if(start>end) return NULL;
int max = -1;
int flag;
for(int i=start;i<=end;i++){
if(nums[i]>max){
max = nums[i];
flag = i;
}
}
TreeNode* root = new TreeNode(nums[flag]);
root->left = sub_construct(nums,start,flag-1);
root->right = sub_construct(nums,flag+1,end);
return root;
}
TreeNode* constructMaximumBinaryTree(vector<int>& nums) {
if(nums.size() == 0) return NULL;
else return sub_construct(nums,0,nums.size()-1);
}
};