代码随想录算法训练营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);
    }
}
相关推荐
Tsuki_tl26 分钟前
【优选算法 — 双指针】经典例题题解+算法总结
算法·蓝桥杯·力扣·刷题·双指针·1024程序员节·优选算法
拓恒技术1 小时前
内河航道无人机智能巡检系统与算法应用
人工智能·深度学习·算法·无人机·智慧城市
如何原谅奋力过但无声1 小时前
【LeetCode hot100】代码随想录未cover部分
数据结构·算法·leetcode
INGNIGHT1 小时前
377.组合总和 Ⅳ(背包)
c++·算法·1024程序员节
拓恒技术2 小时前
城市管理中的无人机AI识别算法:架构、场景与落地
人工智能·算法·视觉检测·无人机·1024程序员节
吴可可1232 小时前
Accumark二次开发环境搭建与API入门
算法
木井巳4 小时前
【动态规划: 线性dp】解码方法
java·算法·leetcode·动态规划·推荐算法
春弦_12 小时前
自用算法整理二
数据结构·算法·图论
hetao173383713 小时前
2026-10-22~23 hetao1733837 的刷题记录
c++·算法
java_nnnn13 小时前
LeetCode刷题滑动窗口(串联所有单词的子串+最小覆盖的子串)Java
算法·leetcode·职场和发展