11.9树Ⅳ

6.14最大二叉树

class Solution {
public:
    TreeNode* constructMaximumBinaryTree(vector<int>& nums) {
        TreeNode* node = new TreeNode(0);
        if(nums.size()==1){//容器中只有一个元素的时候才进入
            node->val = nums[0];
            return node;
        }

        int maxvalue = 0;//最大值
        int maxvalueindex = 0;//最大值索引
        for(int i=0;i<nums.size();i++){ 
            if(nums[i]>maxvalue){
                maxvalue = nums[i];
                maxvalueindex = i;
            }
        }
        node->val = maxvalue;//此时根节点为最大值
        if(maxvalueindex>0){//递归左子树
            vector<int> vec(nums.begin(),nums.begin()+maxvalueindex);
            node->left = constructMaximumBinaryTree(vec);
        }

        if(maxvalueindex<nums.size()-1){//递归右子树
            vector<int> vec(nums.begin()+maxvalueindex+1,nums.end());
            node->right = constructMaximumBinaryTree(vec);
        }
        return node;
    }
};

6.15合并二叉树

class Solution {
public:
    TreeNode* mergeTrees(TreeNode* root1, TreeNode* root2) {
        if(!root1) return root2;//哪个结点不存在,则返回另一个结点并不需要相加
        if(!root2) return root1;
        root1->val += root2->val;
        root1->left = mergeTrees(root1->left,root2->left);//递归左子树
        root1->right = mergeTrees(root1->right,root2->right);
        return root1;
    }
};

6.16二叉搜索树中的搜索

class Solution {//二叉排序树
public:
    TreeNode* searchBST(TreeNode* root, int val) {
        if (root == NULL || root->val == val) return root;
        if (root->val > val) return searchBST(root->left, val);
        if (root->val < val) return searchBST(root->right, val);
        return NULL;
    }
};

6.17验证二叉搜索树

class Solution {
public:
    long long maxval = LONG_MIN;
    bool isValidBST(TreeNode* root) {
        if(!root) return true;
        bool isleft = isValidBST(root->left);
        if(maxval<root->val) //避免出现子树的子树的值小于或者大于祖先结点
            maxval = root->val;
        else
            return false;
        bool isright = isValidBST(root->right);
        return isleft && isright;
    }
};
posted @ 2023-11-10 18:35  Ref-rain-  阅读(7)  评论(0)    收藏  举报