-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path654.cpp
More file actions
25 lines (25 loc) · 706 Bytes
/
Copy path654.cpp
File metadata and controls
25 lines (25 loc) · 706 Bytes
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
// nlogn.cpp
/**
* 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) {
return recursion(nums.begin(), 0, nums.size());
}
TreeNode *recursion(vector<int>::iterator it, int left, int right) {
if (left >= right)
return nullptr;
auto maxIt = max_element(it + left, it + right);
TreeNode *root = new TreeNode(*maxIt);
root->left = recursion(it, left, (int)(maxIt - it));
root->right = recursion(it, (int)(maxIt - it) + 1, right);
return root;
}
};