代码随想录算法训练营第二十 | ● 654.最大二叉树 ● 617.合并二叉树 ● 700.二叉搜索树中的搜索 ● 98.验证二叉搜索树

654.最大二叉树

题目链接/文章讲解: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());
    }
};

617.合并二叉树

题目链接/文章讲解: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; 
    }
};

700.二叉搜索树中的搜索

题目链接/文章讲解: 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;
    }
};

98.验证二叉搜索树

题目链接/文章讲解: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;
    }
};
  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值