代码随想录算法训练营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);
    }
}
相关推荐
小白菜又菜2 小时前
Leetcode 3370. Smallest Number With All Set Bits
算法·leetcode·职场和发展
星谷罗殇3 小时前
(七)TRPO 算法 & PPO 算法
算法·机器学习
国服第二切图仔5 小时前
Rust开发之使用Trait对象实现多态
开发语言·算法·rust
电鱼智能的电小鱼5 小时前
基于电鱼 ARM 工控机的井下AI故障诊断方案——让煤矿远程监控更智能、更精准
网络·arm开发·人工智能·算法·边缘计算
s砚山s5 小时前
代码随想录刷题——二叉树篇(一)
c++·算法·leetcode
贝塔实验室8 小时前
LDPC 码的构造方法
算法·fpga开发·硬件工程·动态规划·信息与通信·信号处理·基带工程
Greedy Alg8 小时前
LeetCode 287. 寻找重复数
算法
2501_938791229 小时前
逻辑回归与KNN在低维与高维数据上的分类性能差异研究
算法·分类·逻辑回归
南方的狮子先生9 小时前
【深度学习】60 分钟 PyTorch 极速入门:从 Tensor 到 CIFAR-10 分类
人工智能·pytorch·python·深度学习·算法·分类·1024程序员节
报错小能手9 小时前
C++笔记(面向对象)类模板
算法