代码随想录第十九章 | 继续二叉树

今天还是二叉树

 

654. 最大二叉树

class Solution {
    public TreeNode constructMaximumBinaryTree(int[] nums) {
        int n = nums.length;
        return maxTree(nums, 0, n - 1);
    }
    public TreeNode maxTree(int[] nums, int l, int r){
        if(l > r){
            return null;
        }
        int bond = findMax(nums, l, r);
        TreeNode root = new TreeNode(nums[bond]);
        root.left = maxTree(nums, l, bond - 1);
        root.right = maxTree(nums, bond+ 1, r);
        return root;
    }
    public int findMax(int[] nums, int l, int r){
        int max = Integer.MIN_VALUE, maxIndex= l;
        for(int i = l; i<= r; i++){
            if(max < nums[i]){
                max = nums[i];
                maxIndex = i;
            }
        }
        return maxIndex;
    }
}

递归

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){
            return null;
        }
        if(root.val == val){
            return root;
        }
        
        return root.val > val ? searchBST(root.left, val) : searchBST(root.right,val);
    }
}

非常简单的题,注意是二叉搜索树就好

98. 验证二叉搜索树

class Solution {
    public boolean isValidBST(TreeNode root) {
        return test(root, Long.MIN_VALUE, Long.MAX_VALUE);
    }
    public boolean test(TreeNode node, long min, long max){
        if(node == null){
            return true;
        }
        if(node.val <= min || node.val >=max){
            return false;
        }
        return test(node.left, min, node.val) && test(node.right, node.val, max);
    }
}

这道题成为中等题的原因就是边界值

今天还是二叉树的一天,二叉树的内容很多很难,很折磨人

posted @ 2022-10-31 15:24  小猫Soda  阅读(22)  评论(0)    收藏  举报