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

代码随想录算法训练营第二十二天

654.最大二叉树

题目链接:654.最大二叉树
找数组的最大值,最大值左侧是左子树,右侧是右子树。

/**
 * 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* constructMaximumBinaryTree(vector<int>& nums) {
        int max_index =0;
        int rootVal = INT_MIN;
        if(nums.size() == 1)return new TreeNode(nums[0]);

        for(int i =0;i<nums.size();i++){
            if(nums[i]>rootVal){
                rootVal =nums[i];
                max_index = i; 
            }
        }        
        TreeNode* root = new TreeNode(rootVal);
        vector<int> left_nums(nums.begin(),nums.begin()+max_index);
        vector<int> right_nums(nums.begin()+max_index+1,nums.end());
        if(!left_nums.empty())root->left = constructMaximumBinaryTree(left_nums);//在数组传入之前判空,减少一次递归
        if(!right_nums.empty())root->right = constructMaximumBinaryTree(right_nums);
        return root;
    }
};

617.合并二叉树

题目链接:617.合并二叉树

class Solution {
public:
    TreeNode* mergeTrees(TreeNode* root1, TreeNode* root2) {
        if(root1==nullptr)return root2;
        else if (root2 == nullptr)return root1;
        int sumVal = root1->val+root2->val;
        TreeNode* sumroot = new TreeNode(sumVal);
        sumroot->left = mergeTrees(root1->left, root2->left);
        sumroot->right = mergeTrees(root1->right, root2->right);
        return sumroot;
    }
};

700.二叉搜索树中的搜索

题目链接:700.二叉搜索树中的搜索

class Solution {
public:
    TreeNode* result = nullptr;
    TreeNode* searchBST(TreeNode* root, int val) {
        if (root->val == val)
            result = root;
        if (root->left == nullptr && root->right == nullptr)
            return nullptr;
        if (root->left&&root->val > val)
            searchBST(root->left, val);
        else if (root->right&&root->val < val)
            searchBST(root->right, val);
        return result;
    }
};

98.验证二叉搜索树

题目链接:98.验证二叉搜索树
不是只要左节点小于中节点小于右节点就是二叉搜索树,左子树都要小于中节点,右子树都要大于中节点。不能直接用左右节点和中节点做比较。

class Solution {
public:
    TreeNode* pre = nullptr;
    bool isValidBST(TreeNode* root) {
        if(!root)return true;
        bool left_b = isValidBST(root->left);
        if(pre&&pre->val>=root->val)return false;
        pre =root;
        bool right_b = isValidBST(root->right);
        return left_b&& right_b;
    }
};

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值