代码随想录算法训练营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);
    }
}
相关推荐
All for pursuit.7 分钟前
【动态规划-8】152.乘积最大子数组
数据结构·c++·算法·leetcode·动态规划
信奥卷王10 分钟前
[GESP202512 六级] 路径覆盖
数据结构·算法
Lazionr26 分钟前
手撕 unordered_set 和 unordered_map,剖析哈希表底层实现
c++·算法
0+11137 分钟前
算法 --归并排序
数据结构·算法·排序算法
Run_Teenage44 分钟前
算法:树的重心、树的直径
算法
专注仿真1 小时前
高代价计算后置:探测、交战、毁伤三条链路的统一设计哲学
算法·探测·毁伤
xie0510_1 小时前
Any类简要实现
开发语言·c++·算法
在所不辞兄1 小时前
为什么PINN非常适合求解有限元模型
人工智能·深度学习·神经网络·算法·机器学习
一棵树73511 小时前
数据结构闲聊
数据结构·算法
bro_Java6661 小时前
《二叉树的基础知识、操作方法与代码示例》
java·数据结构·算法·广度优先