代码随想录-2023/07/17

77 阅读2分钟

二叉树的应用

654.最大二叉树

  1. 递归法构造二叉树, 之前是通过中序和后序构造二叉树, 本题目是每次找区间内最大值构造二叉树, 然后递归的处理最大值左边和右边的元素
  2. 在一个数组上递归, 所以只需要一个区间即可, 每次在当前区间内找到最大值以及其索引

代码:

class Solution {
    public TreeNode constructMaximumBinaryTree(int[] nums) {
        return dfs(nums, 0, nums.length);
    }
    public TreeNode dfs(int[] nums, int start, int end) {
        if(start >= end) return null;
        // 找最大值
        int max_index = start, max_value = nums[start];
        for(int i=start; i<end; i++) {
            if(nums[i] > max_value){
                max_index = i;
                max_value = nums[i];
            }
        }
        TreeNode root = new TreeNode(max_value);
        root.left = dfs(nums, start, max_index);
        root.right = dfs(nums, max_index+1, end);
        return root;
    }
}

617.合并二叉树

  1. 递归: 两个节点同时遍历, 若当前两个节点都为空则返回null, 若一个为空, 另外一个不为空, 则返回不为空的那个, 若两个都不为空, 则构造节点, 同时递归的构造子节点

代码:

class Solution {
    public TreeNode mergeTrees(TreeNode root1, TreeNode root2) {
        return dfs(root1, root2);
    }

    public TreeNode dfs(TreeNode root1, TreeNode root2) {
        if(root1 == null) return root2;
        if(root2 == null) return root1;
        TreeNode root = new TreeNode(root1.val + root2.val);
        root.left = dfs(root1.left, root2.left);
        root.right = dfs(root1.right, root2.right);
        return root;
    }

}

700.二叉搜索树中的搜索

  1. 递归法: 利用二叉搜索树特性进行搜索即可, 若遇到null, 则代表无该元素, 搜索失败

代码:

class Solution {
    public TreeNode searchBST(TreeNode root, int val) {
        if(root == null) return null;
        if(val > root.val){
            return searchBST(root.right, val);
        }else if(val < root.val){
            return searchBST(root.left, val);
        }else {
            return root;
        }

    }
}

98.验证二叉搜索树

二叉搜索树特性: 中序遍历为升序 递归法中序遍历, 用一个指针记录遍历的当前节点的上一个节点, 然后在中间改变指针指向, 在当前节点判断是否为升序

代码:

class Solution {
    // 二叉搜索树特性---中序遍历为升序
    TreeNode pre = null;
    public boolean isValidBST(TreeNode root) {
       return dfs(root);
    }
    public boolean dfs(TreeNode root) {
        if(root == null) return true;
        
        boolean left = isValidBST(root.left);

        if(pre != null && root.val <= pre.val) return false;
        else pre = root;
        
        boolean right = isValidBST(root.right);
        

        return left && right;
    }
}