【算法训练记录——Day20】


目标:
● 654.最大二叉树
● 617.合并二叉树
● 700.二叉搜索树中的搜索
● 98.验证二叉搜索树

654.最大二叉树

在这里插入图片描述
思路:
1. 找到最大值
2. 若数组元素为1,返回,否则继续
3. 构建左子树数组
4. 构建右子树数组

	TreeNode* recursion(vector<int>& nums) {
        int rootIndex = -1;
        int size = nums.size();
        int maxNum = INT_MIN;
        for(int i = 0; i < size; i++) {
            if(maxNum < nums[i]) {
                maxNum = nums[i];
                rootIndex = i;
            }
        }
        TreeNode* root = new TreeNode(maxNum);
        if(size == 1) return root;
        // 左闭右开
        vector<int> leftNums(nums.begin(), nums.begin() + rootIndex);
        vector<int> rightNums(nums.begin() + rootIndex + 1, nums.end());
        
        if(leftNums.size() > 0) root->left = recursion(leftNums);
        if(rightNums.size() > 0) root->right = recursion(rightNums);
        return root;
    }
    TreeNode* constructMaximumBinaryTree(vector<int>& nums) {
        return recursion(nums);
    }

617.合并二叉树

在这里插入图片描述
思路:两节点重叠

  1. 若其中一个节点为空,返回另一节点
  2. 若两个都不为空,构造节点
	TreeNode* recursion(TreeNode* root1, TreeNode* root2, TreeNode* root) {
        if(root1 == nullptr) {
            return root2;
        }
        if(root2 == nullptr) {
            return root1;
        }
        
        root = new TreeNode(root1->val + root2->val);
        root->left = recursion(root1->left, root2->left, root);
        root->right = recursion(root1->right, root2->right, root);
        
        return root;
    }
    TreeNode* mergeTrees(TreeNode* root1, TreeNode* root2) {
        TreeNode* root = nullptr;
        return recursion(root1, root2, root);      
    }

700.二叉搜索树中的搜索

在这里插入图片描述
思路:考二叉搜索树的概念、特性

	TreeNode* searchBST(TreeNode* root, int val) {
        if(root == nullptr) return root;
        if(val == root->val)
            return root;
        if(val > root->val)
            return searchBST(root->right, val);
        if(val < root->val)
            return searchBST(root->left, val);
        return nullptr;
    }

98.验证二叉搜索树

思路: 二叉搜索树左子树小于根节点小于右子树,符合中序遍历左根右递增,因此中序遍历二叉树,保存最大值,若当前元素<=最大值,返回false

	long long maxVal = LONG_MIN; // 因为后台测试数据中有int最小值
    bool isValidBST(TreeNode* root) {
        if(root == nullptr) return true;

        bool left = isValidBST(root->left);
        if(maxVal < root->val) maxVal = root->val;
        else return false;
        return left && isValidBST(root->right);
    }
  • 4
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值