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;
    }
}
相关推荐
晚霞的不甘4 分钟前
Flutter for OpenHarmony 实现计算几何:Graham Scan 凸包算法的可视化演示
人工智能·算法·flutter·架构·开源·音视频
㓗冽18 分钟前
60题之内难题分析
开发语言·c++·算法
大江东去浪淘尽千古风流人物20 分钟前
【VLN】VLN仿真与训练三要素 Dataset,Simulators,Benchmarks(2)
深度学习·算法·机器人·概率论·slam
铉铉这波能秀1 小时前
LeetCode Hot100数据结构背景知识之字典(Dictionary)Python2026新版
数据结构·python·算法·leetcode·字典·dictionary
蜡笔小马1 小时前
10.Boost.Geometry R-tree 空间索引详解
开发语言·c++·算法·r-tree
我是咸鱼不闲呀1 小时前
力扣Hot100系列20(Java)——[动态规划]总结(下)( 单词拆分,最大递增子序列,乘积最大子数组 ,分割等和子集,最长有效括号)
java·leetcode·动态规划
唐梓航-求职中1 小时前
编程-技术-算法-leetcode-288. 单词的唯一缩写
算法·leetcode·c#
仟濹1 小时前
【算法打卡day3 | 2026-02-08 周日 | 算法: BFS】3_卡码网99_计数孤岛_BFS | 4_卡码网100_最大岛屿的面积DFS
算法·深度优先·宽度优先
Ll13045252981 小时前
Leetcode二叉树part4
算法·leetcode·职场和发展
颜酱1 小时前
二叉树遍历思维实战
javascript·后端·算法