代码随想录算法训练营第20天|654.最大二叉树、617.合并二叉树、700.二叉搜索树中的搜索、98.验证二叉搜索树

64 阅读1分钟

今日内容 

●  654.最大二叉树 

●  617.合并二叉树 

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

●  98.验证二叉搜索树

654. 最大二叉树

class Solution {
    //也是构建二叉树的题,通过下标来划分从而不需要深拷贝数组
    public TreeNode constructMaximumBinaryTree(int[] nums) {
        return recur(nums, 0, nums.length);
    }
    //左闭右开
    private TreeNode recur(int[] nums, int leftIndex, int rightIndex) {
        if(rightIndex - leftIndex < 1) {
            return null;
        }
        if(rightIndex - leftIndex == 1) {
            return new TreeNode(nums[leftIndex]);
        }
        int maxNodeIndex = leftIndex;
        int maxNodeVal = nums[leftIndex];
        for(int i = leftIndex + 1; i < rightIndex; i++) {
            if(nums[i] > maxNodeVal) {
                maxNodeVal = nums[i];
                maxNodeIndex = i;
            }
        }
        TreeNode root = new TreeNode(maxNodeVal);
        root.left = recur(nums, leftIndex, maxNodeIndex);
        root.right = recur(nums, maxNodeIndex + 1, rightIndex);
        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. 二叉搜索树中的搜索

利用BST的性质,然后要注意要有个res来承接返回的结果,函数是得有返回值的

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. 验证二叉搜索树

利用bst的性质,都放入一个数组中,然后进行判断

class Solution {
    ArrayList<Integer> arr;
    public boolean isValidBST(TreeNode root) {
        arr = new ArrayList<>();
        inOrder(root);
        for(int i = 0; i < arr.size() - 1; i++) {
            if(arr.get(i) >= arr.get(i+1)) {
                return false;
            }
        }
        return true;
    }
    private void inOrder(TreeNode root) {
        if(root == null) {
            return;
        }
        inOrder(root.left);
        arr.add(root.val);
        inOrder(root.right);
    }
}