-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathconstructMaximumBinaryTree.cpp
More file actions
53 lines (51 loc) · 1.77 KB
/
constructMaximumBinaryTree.cpp
File metadata and controls
53 lines (51 loc) · 1.77 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
/**
* 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* helper(vector<int>& nums, int l, int r) {
if (l > r) return nullptr;
else if (l == r) return new TreeNode(nums[l]);
int idx = std::max_element(nums.begin() + l, nums.begin() + r + 1) - nums.begin();
TreeNode *root = new TreeNode(nums[idx]);
root->left = helper(nums, l, idx - 1);
root->right = helper(nums, idx + 1, r);
return root;
}
TreeNode* constructMaximumBinaryTree(vector<int>& nums) {
return helper(nums, 0, nums.size() - 1);
}
};
// Monotonic Stack
class Solution {
public:
TreeNode* constructMaximumBinaryTree(vector<int>& nums) {
int n = nums.size();
vector<int> stk;
vector<TreeNode*> tree(n);
for (int i = 0; i < n; ++i) {
tree[i] = new TreeNode(nums[i]);
while (!stk.empty() && nums[i] > nums[stk.back()]) {
tree[i]->left = tree[stk.back()];
stk.pop_back();
}
if (!stk.empty()) {
tree[stk.back()]->right = tree[i];
}
stk.push_back(i);
}
return tree[stk[0]];
}
};
// 作者:LeetCode-Solution
// 链接:https://leetcode.cn/problems/maximum-binary-tree/solution/zui-da-er-cha-shu-by-leetcode-solution-lbeo/
// 来源:力扣(LeetCode)
// 著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。