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

80 阅读1分钟

654. 最大二叉树

构造树一般采用的是前序遍历,因为先构造中间节点,然后递归构造左子树和右子树。

class Solution {
    public TreeNode constructMaximumBinaryTree(int[] nums) {
        return build(nums, 0, nums.length - 1);
    }
    private TreeNode build(int[] nums, int low, int high){
        if(low > high)return null;

        int index = -1;
        int maxNum = Integer.MIN_VALUE;
        for(int i = low; i <= high; i++){
            if(nums[i] > maxNum){
                maxNum = nums[i];
                index = i;
            }
        }

        TreeNode root = new TreeNode(maxNum);
        
        root.left = build(nums, low, index - 1);
        root.right = build(nums, index + 1, high);

        return root;
    }
}

617. 合并二叉树

class Solution {
    public TreeNode mergeTrees(TreeNode root1, TreeNode root2) {
        if(root1 == null)return root2;
        if(root2 == null)return root1;

        root1.val += root2.val;
        root1.left = mergeTrees(root1.left , root2.left);
        root1.right = mergeTrees(root1.right, root2.right);

        return root1;
    }
}

700. 二叉搜索树中的搜索

class Solution {
    public TreeNode searchBST(TreeNode root, int val) {
        if(root == null || root.val == val)return root;

        TreeNode res = null;
        if(root.val > val)res = searchBST(root.left, val);
        if(root.val < val)res = searchBST(root.right, val);

        return res;
    }
}

98. 验证二叉搜索树

class Solution {
    public boolean isValidBST(TreeNode root) {
        return isValidBST(root, null, null);
    }
    private boolean isValidBST(TreeNode root, TreeNode low, TreeNode high){
        if(root == null)return true;

        if(low != null && root.val <= low.val)return false;
        if(high != null && root.val >= high.val)return false;

        return isValidBST(root.left, low, root) && isValidBST(root.right, root, high);
    }
}