654. 最大二叉树

Problem: 654. 最大二叉树

思路

这里没有搞明白vector<int> left(nums.begin(), nums.begin() + maxIndex);为什么是nums.begin() + maxIndex而不是nums.begin() + maxIndex - 1

复杂度

时间复杂度:

添加时间复杂度, 示例: $O(n)$

空间复杂度:

添加空间复杂度, 示例: $O(n)$

Code

[]
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
/**
* 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) {
TreeNode* node = new TreeNode(0);
// 找到最大数和索引
int maxIndex = 0, maxNum = 0;
for (int i = 0; i < nums.size(); i++) {
if (nums[i] > maxNum) {
maxNum = nums[i];
maxIndex = i;
}
}
// 划分左右区间
node->val = maxNum;
if (maxIndex > 0) {
vector<int> left(nums.begin(), nums.begin() + maxIndex);
node->left = constructMaximumBinaryTree(left);
}
if (maxIndex < nums.size() - 1) {
vector<int> right(nums.begin() + maxIndex + 1, nums.end());
node->right = constructMaximumBinaryTree(right);
}
return node;
}
};