代码随想录算法训练营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);
    }
}
相关推荐
纪念 2298 分钟前
C++ 算法模板与错题 (前缀和)
开发语言·c++·算法
罗西的思考15 分钟前
【轻量化复刻大模型 / π0.5】(4)处理输入
人工智能·算法·机器学习
饮水桶_T1 小时前
DUNE:基于依赖图传播的Agent派生记忆一致性更新机制 笔记
开发语言·笔记·算法·电脑
Navigator_Z1 小时前
LeetCode //C - 1332. Remove Palindromic Subsequences
c语言·算法·leetcode
Code_Solitude1 小时前
c语言:期末复习(7)
c语言·开发语言·算法
金榜题名萱1 小时前
蓝桥杯 - 旗帜
c语言·数据结构·c++·算法·蓝桥杯
LabVIEW开发2 小时前
探测器脉冲只有 500 ns,谱线要分 2048 道:LabVIEW 怎么把振动台和计数器锁在同一根时间轴上
人工智能·算法·labview
小O的算法实验室3 小时前
SEVC,面向拥塞感知的无人机-卡车协同路径规划的深度强化学习框架
算法
醉颜凉3 小时前
区块链不可篡改机制全解析:从哈希锁链到51%攻击
算法·区块链·哈希算法