代码随想录算法训练营Day15

654.最大二叉树

力扣题目链接:. - 力扣(LeetCode)

前序递归、循环不变量

java 复制代码
class Solution {
    public TreeNode constructMaximumBinaryTree(int[] nums) {
        return findmax(nums,0,nums.length);
    }
    public TreeNode findmax(int[] nums,int leftindex,int rightindex){
        if(rightindex==leftindex){
            return null;
        }
        if(rightindex-leftindex==1){
            return new TreeNode(nums[leftindex]);
        }
        int max=nums[leftindex];
        int maxindex=leftindex;
        for(int i=leftindex;i<rightindex;i++){
            if(nums[i]>max){
                max=nums[i];
                maxindex=i;
            }
        }
        TreeNode root=new TreeNode(max);
        root.left=findmax(nums,leftindex,maxindex);
        root.right=findmax(nums,maxindex+1,rightindex);
        return root;
    }
}

617.合并二叉树

力扣题目链接:. - 力扣(LeetCode)​​​​​​

前序递归

java 复制代码
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.二叉搜索树中的搜索

力扣题目链接:. - 力扣(LeetCode)

java 复制代码
class Solution {
    public TreeNode searchBST(TreeNode root, int val) {
        if(root==null){
            return null;
        }
        if(val>root.val){
            return searchBST(root.right,val);
        }
        if(val<root.val){
            return searchBST(root.left,val);
        }
        return root;
    }
}

98.验证二叉搜索树

力扣题目链接:. - 力扣(LeetCode)

中序递归

java 复制代码
class Solution {
    public boolean isValidBST(TreeNode root) {
        List<Integer> res=new ArrayList<>();
        midorder(root,res);
        for(int i=0;i<res.size()-1;i++){
            if(res.get(i)>=res.get(i+1)){
                return false;
            }
        }
        return true;
    }
    public void midorder(TreeNode root,List<Integer> res){
        if(root==null){
            return;
        }
        midorder(root.left,res);
        res.add(root.val);
        midorder(root.right,res);
    }
}
相关推荐
学不动CV了2 小时前
C语言32个关键字
c语言·开发语言·arm开发·单片机·算法
小屁孩大帅-杨一凡2 小时前
如何解决ThreadLocal内存泄漏问题?
java·开发语言·jvm·算法
Y1nhl4 小时前
力扣_二叉树的BFS_python版本
python·算法·leetcode·职场和发展·宽度优先
向阳逐梦5 小时前
PID控制算法理论学习基础——单级PID控制
人工智能·算法
2zcode5 小时前
基于Matlab多特征融合的可视化指纹识别系统
人工智能·算法·matlab
Owen_Q6 小时前
Leetcode百题斩-二分搜索
算法·leetcode·职场和发展
矢志航天的阿洪6 小时前
蒙特卡洛树搜索方法实践
算法
UnderTheTime7 小时前
2025 XYD Summer Camp 7.10 筛法
算法
zstar-_7 小时前
Claude code在Windows上的配置流程
笔记·算法·leetcode
圆头猫爹7 小时前
第34次CCF-CSP认证第4题,货物调度
c++·算法·动态规划