-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathMaximumBinaryTree.cpp
112 lines (86 loc) · 2.32 KB
/
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
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
<<<<<<< HEAD
/**
* 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 findmax(vector<int>& nums,int l,int r){
// if(l==r)
// return l;
int j;
int mx=INT_MIN;
for(int i=l;i<=r;i++){
if(nums[i]>mx){
mx=nums[i];
j=i;
}
}
return j;
}
TreeNode* MaxTree(vector<int>& nums,int l,int r){
int mx=findmax(nums,l,r);
// cout << l << " " << r << " " << mx << endl;
TreeNode* root = new TreeNode(nums[mx]);
if(mx>l)
root->left=MaxTree(nums,l,mx-1);
else
root->left=NULL;
if(mx<r)
root->right=MaxTree(nums,mx+1,r);
else
root->right=NULL;
return root;
}
TreeNode* constructMaximumBinaryTree(vector<int>& nums) {
return MaxTree(nums,0,nums.size()-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:
int findmax(vector<int>& nums,int l,int r){
// if(l==r)
// return l;
int j;
int mx=INT_MIN;
for(int i=l;i<=r;i++){
if(nums[i]>mx){
mx=nums[i];
j=i;
}
}
return j;
}
TreeNode* MaxTree(vector<int>& nums,int l,int r){
int mx=findmax(nums,l,r);
// cout << l << " " << r << " " << mx << endl;
TreeNode* root = new TreeNode(nums[mx]);
if(mx>l)
root->left=MaxTree(nums,l,mx-1);
else
root->left=NULL;
if(mx<r)
root->right=MaxTree(nums,mx+1,r);
else
root->right=NULL;
return root;
}
TreeNode* constructMaximumBinaryTree(vector<int>& nums) {
return MaxTree(nums,0,nums.size()-1);
}
>>>>>>> 20843e6664516c6814c0e970cfafb680d978dfd5
};