解题思路:
本质上是利用分治思想解决的问题,首先找到数组的最大值生成节点,然后再分别向最大值的左右区间进行相同的操作,返回左右子节点,代码如下:
/**
* 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) {
return construct(nums, 0, nums.size() - 1);
}
TreeNode* construct(vector<int>& nums, int left, int right) {
if(left > right) {
return nullptr;
}
int index = left;
for(int i = left + 1; i <= right; i ++) {
if(nums[i] > nums[index]) {
index = i;
}
}
TreeNode* node = new TreeNode(nums[index]);
node->left = construct(nums, left, index - 1);
node->right = construct(nums,index + 1, right);
return node;
}
};