leetcode-15-[654]最大二叉树[617]合并二叉树[700]二叉搜索树中的搜索[98]验证二叉搜索树

一、[654]最大二叉树

注意:可以与后序中序建树一起写,思想类似

java 复制代码
class Solution {
    public TreeNode constructMaximumBinaryTree(int[] nums) {
        return traversal(nums,0, nums.length);
    }
    TreeNode traversal(int[] nums,int begin,int end){
        //左闭右开
        if(begin>=end){
            return null;
        }
        if(end-begin==1){
            return new TreeNode(nums[begin]);
        }
        int max=nums[begin];
        int index=begin;
        for(int i=begin;i<end;i++){
            if(nums[i]>max){
                max=nums[i];
                index=i;
            }
        }
        TreeNode root=new TreeNode(max);
        root.left=traversal(nums,begin,index);
        root.right=traversal(nums,index+1,end);
        return root;
    }
}

二、[617]合并二叉树

注意:也可以新建树来存储节点

java 复制代码
class Solution {
    public TreeNode mergeTrees(TreeNode root1, TreeNode root2) {
        if(root1==null){
            return root2;
        }
        if(root2==null){
            return root1;
        }
        root1.val= root1.val+ root2.val;
        root1.left=mergeTrees(root1.left,root2.left);
        root1.right=mergeTrees(root1.right,root2.right);
        return root1;
    }
}

三、[700]二叉搜索树中的搜索

重点;利用二叉搜索树的特性

本题解法多样。

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

    }
}

四、[98]验证二叉搜索树

重点:类似于数组的双指针

中序遍历!!!

java 复制代码
class Solution {
    TreeNode pre=null;
    public boolean isValidBST(TreeNode root) {
        if(root==null){
            return true;
        }
        //中序遍历!!!!
        //搜索树一般都为中序遍历
        boolean l = isValidBST(root.left);
        if(pre!=null&&pre.val>=root.val)
        {
            return false;
        }
        pre= root;
        boolean r = isValidBST(root.right);
        return l&&r;
    }
}
相关推荐
zheyutao5 小时前
字符串哈希
算法
A尘埃5 小时前
保险公司车险理赔欺诈检测(随机森林)
算法·随机森林·机器学习
大江东去浪淘尽千古风流人物6 小时前
【VLN】VLN(Vision-and-Language Navigation视觉语言导航)算法本质,范式难点及解决方向(1)
人工智能·python·算法
努力学算法的蒟蒻7 小时前
day79(2.7)——leetcode面试经典150
算法·leetcode·职场和发展
2401_841495647 小时前
【LeetCode刷题】二叉树的层序遍历
数据结构·python·算法·leetcode·二叉树··队列
AC赳赳老秦7 小时前
2026国产算力新周期:DeepSeek实战适配英伟达H200,引领大模型训练效率跃升
大数据·前端·人工智能·算法·tidb·memcache·deepseek
2401_841495647 小时前
【LeetCode刷题】二叉树的直径
数据结构·python·算法·leetcode·二叉树··递归
budingxiaomoli7 小时前
优选算法-字符串
算法
我是咸鱼不闲呀7 小时前
力扣Hot100系列19(Java)——[动态规划]总结(上)(爬楼梯,杨辉三角,打家劫舍,完全平方数,零钱兑换)
java·leetcode·动态规划
qq7422349847 小时前
APS系统与OR-Tools完全指南:智能排产与优化算法实战解析
人工智能·算法·工业·aps·排程