参考资料
思路
1. 构造二叉树一般是使用前序遍历(因为前序遍历是中左右,在递归的过程中逐渐向下延申。)
2. 找出向量中的最大元素,记录最大值和对应下标
3. 将最大值赋值给根节点(中),根据最大值的下标划分向量为左子树区间和右子树区间。
4. 将左子树区间和右子树区间作为参数进行递归
代码实现
/**
* 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) {
// 终止条件
if (nums.empty()) return NULL;
// 求出nums向量中的最大值和对应下标
int maxVal = nums[0];
int maxIndex = 0;
for (int i = 1; i < nums.size(); ++i) {
if (nums[i] > maxVal) {
maxVal = nums[i];
maxIndex = i;
}
}
// 返回值
TreeNode* root = new TreeNode(maxVal);
// 根据最大值下标 划分nums为左右区间
vector<int> leftnums (nums.begin(), nums.begin() + maxIndex);
vector<int> rightnums (nums.begin() + maxIndex + 1, nums.end());
// 递归
root->left = constructMaximumBinaryTree(leftnums);
root->right = constructMaximumBinaryTree(rightnums);
return root;
}
};
优化
因为每次递归都需要构建两个新的向量,造成资源浪费。可以在形参中加入两个int类型的数值,记录位置区间大小。
/**
* 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* travel(vector<int> nums, int left, int right) {
// 终止条件
if (left >= right) return NULL;
// 找到区间里的最大值和对应下标
int maxIndex = left;
for (int i = maxIndex + 1; i < right; ++i) {
if (nums[i] > nums[maxIndex]) maxIndex = i;
}
// 中 将最大值传递给根节点
TreeNode* root = new TreeNode(nums[maxIndex]);
// 左区间 递归
root->left = travel(nums, left, maxIndex);
// 右区间 递归
root->right = travel(nums, maxIndex + 1, right);
return root;
}
TreeNode* constructMaximumBinaryTree(vector<int>& nums) {
if (nums.empty()) return NULL;
return travel(nums, 0, nums.size());
}
};