力扣刷题笔记 二叉树篇04——二叉树的合并,公共祖先。BST的搜索,验证,众数

本文总结了二叉树解题的关键点,包括二叉搜索树的中序遍历性质,并提供了六道实战题目,涉及二叉树的合并、搜索、验证二叉搜索树、计算最小绝对差、查找众数以及找到最近公共祖先等核心问题。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

总结先放在前面:

二叉搜索树的中序遍历是递增的

解答二叉树时的一些小技巧与注意点:

题目实战

1.NO.617. 合并二叉树

在这里插入图片描述

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     public int val;
 *     public TreeNode left;
 *     public TreeNode right;
 *     public TreeNode(int val=0, TreeNode left=null, TreeNode right=null) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */
public class Solution {
   
    public TreeNode MergeTrees(TreeNode root1, TreeNode root2) {
   
        if(root1==null){
   
            return root2;
        }
        if(root2==null){
   
            return root1;
        }
        TreeNode root = new TreeNode(root1.val+root2.val);
        root.left=MergeTrees(root1.left,root2.left);
        root.right=MergeTrees(root1.right,root2.right);
        return root;
    }
}

在这里插入图片描述

2.NO.700. 二叉搜索树中的搜索

在这里插入图片描述

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     public int val;
 *     public TreeNode left;
 *     public TreeNode right;
 *     public TreeNode(int val=0, TreeNode left=null, TreeNode right=null) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */
public class Solution {
   
    public TreeNode SearchBST(TreeNode root, int val) {
   
        if(root==null){
   
            return null;
        }
        if(root.val==val){
   
            return root;
        }
        return root.val<val?SearchBST(root.right,val)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值