代码随想录Day17

题目列表

  • 654.最大二叉树(LeetCode)
  • 617.合并二叉树(LeetCode)
  • 700.二叉搜索树中的搜索(LeetCode)
  • 98.验证二叉搜索树(LeetCode)

解题过程

654.最大二叉树

题目描述

image

解题思路

和105 106思路类似,稍微简单一些。关键点还是在于确定中间节点、左子树、右子树,这样不断递归。

代码展示

class Solution {
    public TreeNode constructMaximumBinaryTree(int[] nums) {
        
        return construct(nums, 0, nums.length);
    }
    public TreeNode construct(int[] nums, int begin ,int end){
        if(begin >= end) return null;
        if(begin == end - 1) return new TreeNode(nums[begin]);

        int rootValue = 0;
        int index = 0;
        for(int i = begin; i < end; i++){
            if(nums[i] > rootValue){
                rootValue = nums[i];
                index = i;
            }
        }
        TreeNode root = new TreeNode(rootValue);

        root.left = construct(nums, begin, index);
        root.right = construct(nums, index + 1, end);
        
        return root;
    }
}

617.合并二叉树

题目描述

image

解题思路

关键点在于两颗二叉树要同步递归遍历,这样才能对应到。

做题时有担心深度相差太大会不会遍历不到,后来反应过来在返回一个节点的时候相当于以这个节点为根的子树都会“跟过来”,只是为另一颗同样的位置的节点已经为null了,所以没有再继续递归的必要。
image

代码展示

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.二叉搜索树中的搜索

题目描述

image

解题思路

利用二叉树的特性即可,不用遍历整棵树,一条路走到头。

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

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

98.验证二叉搜索树

题目描述

image

解题思路

熬穿了又,改日写双指针法思路

代码展示

class Solution {
    TreeNode pre;
    public boolean isValidBST(TreeNode root) {
        if(root == null) return true;

        boolean left = isValidBST(root.left);

        if(pre != null && root.val <= pre.val){
            return false;
        }
        pre = root;

        boolean right = isValidBST(root.right);
        return left && right;
    }
}

参考资料

代码随想录

posted @ 2025-05-15 01:28  cbdsszycfs  阅读(8)  评论(0)    收藏  举报