本文最后更新于620 天前,其中的信息可能已经过时,如有错误请发送邮件到tomding1065@gmail.com
题目链接/文章讲解:https://programmercarl.com/0654.%E6%9C%80%E5%A4%A7%E4%BA%8C%E5%8F%89%E6%A0%91.html
视频讲解:https://www.bilibili.com/video/BV1MG411G7ox
1.这个题和昨天做的后序中序构造二叉树的题类似,有了昨天的基础今天理解起来这个题十分轻松,所以我挑战了一下,选择了优化代码,减少内存消耗的做法,就是通过两个指针改变每次递归的数组。过程并不轻松,发现了一个问题感觉自己对于递归的理解程度还需要一些时间,就是这个部分
int maxIndex = left;
for(int i = left + 1;i< right; ++i){
if(nums[i] > nums[maxIndex])maxIndex = i;
}
TreeNode* node = new TreeNode(nums[maxIndex]);
我发现,我自己写的是int maxIndex = 0;但是文档给的是int maxIndex = left我仔细的去看代码,终于了解了在递归过程中遍历的开头是变化的,不一定总是0 所以left合适。
CPP
/**
* 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* construct(vector<int>&nums , int left , int right){
if(left >= right)return NULL;
int maxIndex = left;
for(int i = left + 1;i< right; ++i){
if(nums[i] > nums[maxIndex])maxIndex = i;
}
TreeNode* node = new TreeNode(nums[maxIndex]);
node->left = construct(nums , left , maxIndex);
node->right = construct(nums , maxIndex + 1 , right);
return node;
}
TreeNode* constructMaximumBinaryTree(vector<int>& nums) {
return construct(nums , 0 , nums.size());
}
};