-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path654. Maximum Binary Tree.cpp
More file actions
34 lines (31 loc) · 1 KB
/
654. Maximum Binary Tree.cpp
File metadata and controls
34 lines (31 loc) · 1 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
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
TreeNode* constructMaximumBinaryTree(vector<int>& nums) {
return constructNode(nums, 0, nums.size()-1);
}
TreeNode* constructNode(vector<int>& nums, int l ,int h){
if(l > h) return nullptr;
int index = -1, maxval = -1;
for(int i = l; i<=h ; ++i){
if (nums[i] > maxval){
maxval = nums[i];
index = i;
}
}
TreeNode* root = new TreeNode(maxval);
root->left = constructNode(nums, l ,index - 1);
root->right = constructNode(nums, index + 1 ,h);
return root;
}
};