代码随想录day20

654最大二叉树

class Solution {
public:
    TreeNode* constructMaximumBinaryTree(vector<int>& nums) {
        if (nums.empty()) return NULL;
        int mnum=0;
        int index=0;
        for(int i=0;i<nums.size();i++)
        {
            if(nums[i]>mnum)
            {
                mnum=nums[i];
                index=i;
            }
        }

        TreeNode* root=new TreeNode(mnum);
        //index==0的话只有右子树了
        if(index>0)
        {
            vector<int>leftNums(nums.begin(), nums.begin() + index);
            root->left=constructMaximumBinaryTree(leftNums);
        }

        if(index<nums.size()-1) 
        {
            vector<int> rightNums(nums.begin() + index + 1, nums.end());
            root->right = constructMaximumBinaryTree(rightNums);
        }
        return root;
    }
};

617合并二叉树

class Solution {
public:
    TreeNode* mergeTrees(TreeNode* t1, TreeNode* t2) {
        if (t1 == NULL) return t2;
        if (t2 == NULL) return t1;
        TreeNode* root = new TreeNode(0);
        root->val = t1->val + t2->val;
        root->left = mergeTrees(t1->left, t2->left);
        root->right = mergeTrees(t1->right, t2->right);
        return root;
    }
};

700 二叉搜索树中的搜索

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

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

98 验证二叉搜索树

class Solution {
public:
    bool isValidBST(TreeNode* root) 
    {
        return isValid(root, nullptr, nullptr);
    }
    bool isValid(TreeNode* root, TreeNode* min, TreeNode* max) 
    {
    if (root == nullptr) return true;

    if (min != nullptr && root->val <= min->val) return false;   
    if (max != nullptr && root->val >= max->val) return false;
    return isValid(root->left, min, root) 
        && isValid(root->right, root, max);
    }
};

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值