-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path654. Maximum Binary Tree
More file actions
53 lines (48 loc) · 1.59 KB
/
654. Maximum Binary Tree
File metadata and controls
53 lines (48 loc) · 1.59 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
44
45
46
47
48
49
50
51
52
53
654. Maximum Binary Tree
You are given an integer array nums with no duplicates. A maximum binary tree can be built recursively from nums using the following algorithm:
Create a root node whose value is the maximum value in nums.
Recursively build the left subtree on the subarray prefix to the left of the maximum value.
Recursively build the right subtree on the subarray suffix to the right of the maximum value.
Return the maximum binary tree built from nums.
Solution::
/**
* 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) {}
* };
*/
#pragma gcc optimize("03")
auto init =[](){
ios::sync_with_stdio(0);
cin.tie(0);
cout.tie(0);
return 'c';
}();
class Solution {
int maxNum(vector<int>& nums, int i, int j){
int ans = i;
for(;i <= j; i++){
if(nums[i] > nums[ans]){
ans = i;
}
}
return ans;
}
TreeNode * solve(vector<int>&nums , int l , int u){
if(u<l)return NULL;
int k =maxNum(nums , l ,u);
TreeNode * root = new TreeNode(nums[k]);
root->left = solve(nums ,l ,k-1 );
root->right = solve(nums ,k+1 , u );
return root;
}
public:
TreeNode* constructMaximumBinaryTree(vector<int>& nums) {
return solve(nums , 0 , nums.size()-1);
}
};