题目链接:
https://leetcode-cn.com/problems/maximum-binary-tree/
题目要求:
C++代码实现:
/**
* 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:
//digui
TreeNode* digui(vector<int>& nums,int begin,int end){
if(begin > end){
return nullptr;
}
//得到当前范围内的最大值索引
int maxIndex = getCurrIndex(nums,begin,end);
//构造根节点
TreeNode* root = new TreeNode(nums[maxIndex]);
root->left = digui(nums,begin,maxIndex - 1);
root->right = digui(nums,maxIndex + 1,end);
return root;
}
//得到最大索引值的方法
int getCurrIndex(vector<int>& nums,int begin,int end){
int maxIndex = INT_MIN;
int maxNum = INT_MIN;
for(int i = begin;i <= end;i++){
if(nums[i] > maxNum){
maxIndex = i;
maxNum = nums[i];
}
}
return maxIndex;
}
TreeNode* constructMaximumBinaryTree(vector<int>& nums) {
int n = nums.size();
TreeNode* root = digui(nums,0,n - 1);
return root;
}
};
AC截图