-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path0654. Maximum Binary Tree.cpp
More file actions
43 lines (34 loc) · 1.11 KB
/
0654. Maximum Binary Tree.cpp
File metadata and controls
43 lines (34 loc) · 1.11 KB
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
42
43
/**
* 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) {
// mando la primera y ultima pos de mi vector
return helpfunction(nums, 0, nums.size()-1);
}
TreeNode* helpfunction(vector<int>& nums, int izq, int der){
// poner null si el de la izq es mayor
if(izq > der){
return NULL;
}
int aux = izq;
// en aux me voy a quedar con la posición con el valor más grande
for(int i = izq; i <= der; i++){
if(nums[i] > nums[aux]){
aux = i;
}
}
// creo un nodo con el valor maximo
TreeNode* root = new TreeNode(nums[aux]);
root->left = helpfunction(nums, izq, aux-1);
root->right = helpfunction(nums, aux+1, der);
return root;
}
};