-
Notifications
You must be signed in to change notification settings - Fork 12
/
MaximumBinaryTree.cpp
41 lines (34 loc) · 988 Bytes
/
MaximumBinaryTree.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
/**
* 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:
int index(vector<int>& nums, int start, int end){
int maxi = start;
for(int i = start+1; i <= end; i++){
if(nums[i] > nums[maxi]){
maxi = i;
}
}
return maxi;
}
TreeNode* makeTree(vector<int>& nums, int start, int end){
if(start > end){
return NULL;
}
int maxi = index(nums, start, end);
TreeNode* root = new TreeNode(nums[maxi]);
root->left = makeTree(nums, start, maxi-1);
root->right = makeTree(nums, maxi+1, end);
return root;
}
TreeNode* constructMaximumBinaryTree(vector<int>& nums) {
return makeTree(nums, 0, nums.size()-1);
}
};