forked from pezy/LeetCode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
solution.h
28 lines (26 loc) · 819 Bytes
/
solution.h
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
#include <vector>
using std::vector;
#include <algorithm>
struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
};
class Solution {
public:
TreeNode* constructMaximumBinaryTree(vector<int>& nums) {
return constructMaximumBinaryTree(nums.cbegin(), nums.cend());
}
private:
using Iter = vector<int>::const_iterator;
TreeNode* constructMaximumBinaryTree(Iter beg, Iter end) {
if (beg == end) return nullptr;
auto max = std::max_element(beg, end);
TreeNode* root = new TreeNode(*max);
auto max_pos = std::distance(beg, max);
root->left = constructMaximumBinaryTree(beg, max);
root->right = constructMaximumBinaryTree(std::next(max), end);
return root;
}
};