给定一个不重复的整数数组 nums 。 最大二叉树 可以用下面的算法从 nums 递归地构建:
创建一个根节点,其值为 nums 中的最大值。
递归地在最大值 左边 的 子数组前缀上 构建左子树。
递归地在最大值 右边 的 子数组后缀上 构建右子树。
返回 nums 构建的 最大二叉树 。
来源:力扣(LeetCode)
解答:
/**
* 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:
vector<int> search(vector<int> nums){
int res = -1;
int pos = -1;
for(int i = 0; i < size(nums); i++){
if(nums[i] >res){
res = nums[i];
pos = i;
}
}
return {res, pos};
}
TreeNode* constructMaximumBinaryTree(vector<int>& nums) {
int index = search(nums)[1];
TreeNode* head = new TreeNode(search(nums)[0]);
vector<int> nums_left,nums_right;
for(int i = 0; i < size(nums); i++){
if(i < index) nums_left.push_back(nums[i]);
if(i > index) nums_right.push_back(nums[i]);
}
if(search(nums_left)[0]!= -1){
head->left = constructMaximumBinaryTree(nums_left);
}
if(search(nums_right)[0]!= -1){
head->right = constructMaximumBinaryTree(nums_right);
}
return head;
}
};