题目链接/文章讲解: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
class Solution {
private:
TreeNode* traversal(vector<int>& nums, int left, int right){
if(left >= right) return nullptr;
int maxValueIndex = left;
for(int i=left+1;i<right;++i){
if(nums[i] > nums[maxValueIndex]) maxValueIndex = i;
}
TreeNode* root = new TreeNode(nums[maxValueIndex]);
//左闭右开[left,maxValueIndex]
root->left = traversal(nums,left,maxValueIndex);
//左闭右开,[maxValueIndex+1,right]
root->right = traversal(nums,maxValueIndex+1, right);
return root;
}
public:
TreeNode* constructMaximumBinaryTree(vector<int>& nums) {
return traversal(nums, 0, nums.size());
}
};
题目链接/文章讲解:https://programmercarl.com/0617.%E5%90%88%E5%B9%B6%E4%BA%8C%E5%8F%89%E6%A0%91.html
视频讲解:https://www.bilibili.com/video/BV1m14y1Y7JK
前序遍历
class Solution {
public:
TreeNode* mergeTrees(TreeNode* root1, TreeNode* root2) {
if(root1 == NULL) return root2;
if(root2 == NULL) return root1;
root1->val +=root2->val;
root1->left = mergeTrees(root1->left, root2->left);
root1->right = mergeTrees(root1->right, root2->right);
return root1;
}
};
题目链接/文章讲解: https://programmercarl.com/0700.%E4%BA%8C%E5%8F%89%E6%90%9C%E7%B4%A2%E6%A0%91%E4%B8%AD%E7%9A%84%E6%90%9C%E7%B4%A2.html
视频讲解:https://www.bilibili.com/video/BV1wG411g7sF
class Solution {
public:
//1.只要找到这个节点就行,不需要输出子树
//2.递归调用,最后输出的和我们的中间递归的数据类型一致,不需要再单独写函数
TreeNode* searchBST(TreeNode* root, int val) {
if(root==NULL || root->val == val) return root;
TreeNode* cur = NULL;
if(root->val > val)
cur = searchBST(root->left, val);
else
cur = searchBST(root->right, val);
return cur;
}
};
题目链接/文章讲解:https://programmercarl.com/0098.%E9%AA%8C%E8%AF%81%E4%BA%8C%E5%8F%89%E6%90%9C%E7%B4%A2%E6%A0%91.html
视频讲解:https://www.bilibili.com/video/BV18P411n7Q4
中序遍历二叉搜索树得到的是一个递增的数组
1.中序遍历;
2.检查是否递增
class Solution {
public:
void traversal(TreeNode* root, vector<int>& res)
{
if(root==NULL) return;
traversal(root->left,res);
res.push_back(root->val);
traversal(root->right,res);
}
bool isValidBST(TreeNode* root) {
vector<int> result;
traversal(root,result);
for(int i=1;i<result.size();i++)
{
if(result[i]<=result[i-1])
return false;
}
return true;
}
};