算法记录Day 19 | 二叉树part06

43 阅读1分钟

算法记录Day 19 | 二叉树part06

LeetCode 654.最大二叉树

题目链接:654. 最大二叉树

题解
class Solution {
   public:
    TreeNode* constructMaximumBinaryTree(vector<int>& nums) {
        TreeNode* root = build(nums, 0, nums.size() - 1);
        return root;
    }

    TreeNode* build(vector<int>& nums, int start, int end) {
        if (start > end) {
            return nullptr;
        }
        int index = start;
        for (int i = start + 1; i <= end; i++) {
            if (nums[i] > nums[index]) {
                index = i;
            }
        }
        TreeNode* root = new TreeNode(nums[index]);
        root->left = build(nums, start, index - 1);
        root->right = build(nums, index + 1, end);
        return root;
    }
};

LeetCode 617.合并二叉树

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

题解
class Solution {
   public:
    TreeNode* mergeTrees(TreeNode* root1, TreeNode* root2) {
        return dfs(root1, root2);
    }

    TreeNode* dfs(TreeNode* root1, TreeNode* root2) {
        if (root1 == nullptr || root2 == nullptr) {
            return root1 == nullptr ? root2 : root1;
        }
        root1->val += root2->val;
        root1->left = dfs(root1->left, root2->left);
        root1->right = dfs(root1->right, root2->right);
        return root1;
    }
};

LeetCode 700.二叉搜索树中的搜索

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

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

LeetCode 98.验证二叉搜索树

题目链接:98. 验证二叉搜索树

题解
class Solution {
   public:
    long pre = LONG_MIN;
    // 中序遍历
    bool isValidBST(TreeNode* root) {
        if (root == nullptr) {
            return true;
        }
        if (!isValidBST(root->left) || root->val <= pre) return false;
        pre = root->val;
        return isValidBST(root->right);
    }
};