LeetCode算法题-Two Sum IV - Input is a BST(Java实现)

RT-Thread新手必看:FMT飞控移植中的5个常见坑及解决方案 本文针对RT-Thread新手在移植FMT开源飞控时遇到的5大核心挑战,提供了深度解决方案。内容涵盖SCons构建系统配置、RT-Thread版本API兼容性处理、BSP与设备驱动适配、TOML系统配置解析以及算法模块集成调试,帮助开发者高效避坑,成功完成飞控移植。 阅读详情

这是悦乐书的第280次更新,第296篇原创

01 看题和准备

今天介绍的是LeetCode算法题中Easy级别的第148题(顺位题号是653)。给定二进制搜索树和目标数,如果BST中存在两个元素,使得它们的总和等于给定目标,则返回true。例如:

    5
   / \
  3   6
 / \   \
2   4   7

目标值:9

输出:true

    5
   / \
  3   6
 / \   \
2   4   7

目标值:28

输出:false

本次解题使用的开发工具是eclipse,jdk使用的版本是1.8,环境是win7 64位系统,使用Java语言编写和测试。

02 第一种解法

判断在给出的一组数据中,是否存在两个数之和等于给出的目标值,只是给出的数据是个二叉搜索树。所以,我们需要先将数据抽出来,遍历二叉树的节点值,然后再去其中找那可能存在的两个数。

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    public boolean findTarget(TreeNode root, int k) {
        Map<Integer, Integer> map = new HashMap<Integer,Integer>();
        preOrder(root, map);
        // 遍历map
        for (Integer key : map.keySet()) {
            // 分两种情况:k由两个相同的节点值之和组成;由不同的节点值之和组成
            if ((k-key == key && map.get(key) >= 2) || (k-key != key && map.containsKey(k-key))) {
                return true;
            }
        }        
        return false;
    }

    // 使用递归,前序遍历,将二叉树的节点值添加进map中
    public void preOrder(TreeNode node, Map<Integer, Integer> map) {
        if (node == null) {
            return ;
        }
        map.put(node.val, map.getOrDefault(node.val, 0)+1);
        preOrder(node.left, map);
        preOrder(node.right, map);
    }
}

03 第二种解法

我们也可以不使用HashMap,直接使用数组,另外,题目还说了此二叉树是个BST,那么它的中序遍历的节点值是有序的,那么我们可以直接使用双指针而不必排序,对所有的节点值直接判断。

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    public boolean findTarget(TreeNode root, int k) {
        List<Integer> list = new ArrayList<Integer>();
        inOrder(root, list);
        // 使用双指针
        int start = 0, end = list.size()-1;
        while (start < end) {
            int sum = list.get(start) + list.get(end);
            if (sum == k) {
                return true;
            } 
            if (sum > k) {
                end--;
            } else {
                start++;
            }
        }
        return false;
    }

    // 使用递归,中序遍历,将二叉树的节点值添加进list中
    public void inOrder(TreeNode node, List<Integer> list) {
        if (node == null) {
            return ;
        }
        // 左子树
        inOrder(node.left, list);
        // 根节点
        list.add(node.val);
        // 右子树
        inOrder(node.right, list);
    }
}

04 第三种解法

我们也可以使用HashSet,思路和第一种解法类似,依旧使用递归遍历BST的节点,但是此解法是直接在递归方法里面做了判断,如果里面存在两个节点值的话,就直接返回true。

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    public boolean findTarget(TreeNode root, int k) {
        Set<Integer> set = new HashSet<Integer>();
        return helper(root, set, k);
    }

    // 使用递归,将二叉树的节点值添加进set中
    public boolean helper(TreeNode node, Set<Integer> set, int k) {
        if (node == null) {
            return false;
        }
        if (set.contains(k-node.val)) {
            return true;
        }
        set.add(node.val);
        return helper(node.left, set, k) || helper(node.right, set, k);
    }
}

05 第四种解法

针对上面的第三种解法,我们可以使用迭代的方式来实现,借助队列来实现。

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    public boolean findTarget(TreeNode root, int k) {
        Set<Integer> set = new HashSet<Integer>();
        Queue<TreeNode> queue = new LinkedList<TreeNode>();
        queue.offer(root);
        while (!queue.isEmpty()) {
            TreeNode node = queue.poll();
            // 判断是否包含另外一个数字
            if (set.contains(k-node.val)) {
                return true;
            }
            set.add(node.val);
            // 将其左右子节点继续入队列
            if (node.left != null) {
                queue.offer(node.left);
            }
            if (node.right != null) {
                queue.offer(node.right);
            }
        }
        return false;
    }
}

06 小结

算法专题目前已日更超过四个月,算法题文章148+篇,公众号对话框回复【数据结构与算法】、【算法】、【数据结构】中的任一关键词,获取系列文章合集。

以上就是全部内容,如果大家有什么好的解法思路、建议或者其他问题,可以下方留言交流,点赞、留言、转发就是对我最大的回报和支持!

基于Harness Engineering构建AI Agent的全自动化CI_CD流水线 AI Agent的CI/CD是指对Agent的全生命周期资产(代码、Prompt、RAG知识库、模型权重、工具配置)进行持续集成、持续测试、持续发布和持续观测的自动化流程,核心目标是在保障发布质量的前提下,最大化提升Agent的迭代效率。 阅读详情

相关推荐

卫星通信链路预算实战:从EIRP到Eb/N0的完整计算指南(含Excel模板)

本文提供了一份卫星通信链路预算的实战指南,详细解析了从EIRP到Eb/N0的完整计算流程。文章重点对比了C波段与Ku波段在应对降雨衰减等动态因素时的不同策略,并分享了包含核心公式的Excel模板,帮助工程师将理论转化为可执行的系统设计依据。

weixin_29230773的博客 534

Java/653. Two Sum IV - Input is a BST 两数之和 IV - 输入 BST

题目     代码部分一(592ms) /** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } ...

qq_38959715的博客 572

1. 基于STM32的1.28寸圆形IPS屏(GC9A01)驱动移植实战:软件SPI与硬件SPI双方案详解

本文详细介绍了如何在STM32平台上为1.28寸圆形IPS屏(GC9A01驱动芯片)移植驱动程序,涵盖软件SPI与硬件SPI两种实现方案。内容从引脚定义、工程搭建、GPIO配置到SPI外设初始化逐步详解,并提供了完整的测试代码,帮助开发者根据项目需求(灵活性或性能)选择合适的通信方式,快速点亮屏幕并集成到智能手表等嵌入式项目中。

weixin_42300144的博客 203

(Java)leetcode-653 Two Sum IV - Input is a BST (两数之和 IV - 输入 BST)

hash!

不思量 214

最终篇——SWAT模型的建立

同理,Soil Data也是同样的方法导入,在Soil Database Options的选项中,选择UserSiol,用同样的方法导入土壤类型,进行重分类。打开窗口后,只定义HRU Thresholdes,其余两个不用设置,设定各数据单元的计算率,这里的10%的意思是计算精度,即分成级HRU计算单元太小,小于平均计算单元的10%,我们就不对这HRU单元进行计算(也就是说太破碎的计算单元不进行计算),若选择0%意味着全部进行计算,需要耗费大量的内存和时间,对计算机要求较高,不建议。

m0_72556434的博客 5621

直流电动机的建模仿真(1)他励,串励和并励电动机建模仿真

本文根据不同励磁方式的直流电动机的接线原理图,建立了相应的数学模型,然后根据与数学模型对应的等效电路以及模拟机械运动方程的等效电路,用Matlab/simulink中的SpecializedPower system库中的电路元件,建立了他励,并励和串励直流电动机的全等效电路仿真模型,经过与Matlab自带的直流电动机仿真模型比较以及仿真实例验证,所建立的仿真模型时完全正确的。

weixin_45670943的博客 7520

leetcode Two Sum IV - Input is a BST 两个数的和

Given a Binary Search Tree and a target number, return true if there exist two elements in the BST such that their sum is equal to the given target. 题意:判断是否可以从二叉搜索树中找到两个数的和等于目标数。 思路: 1. 二叉搜索树中序遍历后得

black_hidden的博客 325

2022年全国职业院校技能大赛 高职组大数据技术与应用卷⑦——解析答案

大数据时代,电商经营模式发生很大改变。在传统运营模式中,缺乏数据积累,人们在做出一些决策行为过程中,更多是凭借个人经验和直觉,发展路径比较自我封闭。而大数据时代,为人们提供一种全新的思路,通过大量的数据分析得出的结果将更加现实和准确。商家可以对客户的消费行为信息数据进行收集和整理,比如消费者购买产品的花费、选择产品的渠道、偏好产品的类型、产品回购周期、购买产品的目的、消费者家庭背景、工作和生活环境、个人消费观和价值观等。通过数据追踪,知道顾客从哪儿来,是看了某网站投放的广告还是通过朋友推荐链接,是新访客还是

我是网络安全兼技能大赛工程师,专注网络安全技术学习与技能大赛实战!持续分享最新的技术文章,帮你少走弯路,一起在技术赛道上进步~ 472

【LeetCode】653. Two Sum IV - Input is a BST

【题目】 Given a Binary Search Tree and a target number, return true if there exist two elements in the BST such that their sum is equal to the given target. Example 1: Input: 5 / \ 3

踏实 谦虚 卓越 640

【PCIe 总线及设备入门学习专栏 6.2 -- PCIe VDM (Vendor Defined Messages)】

在PCIe协议中,Vendor Defined Messages (VDMs) 是一种允许厂商定义和传输特定功能的消息类型。这种机制扩展了标准 PCIe 消息的功能,可以用于实现供应商自定义的功能,例如固件更新、设备配置和诊断信息传输。PCIe VDM 是通过实现的,它遵循 PCIe 协议栈的结构,包括事务层、数据链路层和物理层。

CodingCos的博客 1898

CANoe如何实现TLS协议

TLS,Transport Layer Security,传输层安全协议。是在传输层和应用层之间,为了保证应用层数据能够安全可靠地通过传输层传输且不会泄露的安全防护。

jasonj333 1161

[LeetCode] 653. Two Sum IV - Input is a BST

原题链接: https://leetcode.com/problems/two-sum-iv-input-is-a-bst/ 题目描述 Given a Binary Search Tree and a target number, return true if there exist two elements in the BST such that their sum is equal to t...

Ber03的博客 340

YOLOv10 的损失函数解析

YOLOv10 在 YOLO 系列的演进中进一步优化了任务解耦与动态平衡策略,通过 ​多模态损失融合、自适应样本分配 和 ​轻量化设计,显著提升了检测精度与推理效率。

浩瀚之水的专栏 1378

leetcode 653. Two Sum IV - Input is a BST

Given a Binary Search Tree and a target number, return true if there exist two elements in the BST such that their sum is equal to the given target. Example 1: Input: 5 / \ 3 6 / \

淡然坊 2079

jre9下载 jdk9

(Java SE Runtime Environment 9.0) 9.0u175 官方最新版 【x86|x64】

WINCC7.3破解文件

WINCC7.3硬件够破解文件,有需要的下载!WINCC7.3硬件够破解文件,有需要的下载!

LeetCode 653. 两数之和 IV - 输入 BST(Two Sum IV - Input is a BST)

653. 两数之和 IV - 输入 BST 653. Two Sum IV - Input is a BST 题目描述 给定一个二叉搜索树和一个目标结果,如果 BST 中存在两个元素且它们的和等于给定的目标结果,则返回 true。 LeetCode653. Two Sum IV - Input is a BST简单 案例 1: 输入: 5 / \ 3 6 / \ \ 2...

weixin_30430169的博客 116

IMSL CNL 7.0.0 (x86-64)Crack

IMSL CNL 7.0.0 (x86-64)Crack intel的算法库破解文件,这是C++版本的破解文件

LeetCode-653. Two Sum IV - Input is a BST [C++][Java]

Given therootof a Binary Search Tree and a target numberk, returntrueif there exist two elements in the BST such that their sum is equal to the given target.

贫道绝缘子的博客 259

复分析 阿尔福斯(Ahlfors) 第三版答案 英文

答案分为十章,有部分习题没有答案,全英文复分析阿尔福斯(Ahlfors) 第三版答案

LeetCode. Two Sum系列之IV - Input is a BST

解法一:使用HashSet,在中序遍历树的同时,判断是否在HashSet中已经存在一个值和当前根节点的值相加可以满足等于target。 c++版本: /** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *rig...

wusutata的专栏 216

Leetcode: 653. Two Sum IV - Input is a BST

Leetcode: 653. Two Sum IV - Input is a BST 超时代码:只多了一个bool变量就超时了 import java.util.ArrayList; import java.util.List; public class SumBSt { public boolean findTa...

哎呀妈呀脑壳疼脑壳疼 198

Leetcode 653. Two Sum IV - Input is a BST

Leetcode 653. Two Sum IV - Input is a BST —————————————– Given a Binary Search Tree and a target number, return true if there exist two elements in the BST such that their sum is equal to the g

两鬓已不能斑白的专栏 2074

【LeetCode】653.Two Sum IV - Input is a BST(Easy)解题报告

【LeetCode】653.Two Sum IV - Input is a BST(Easy)解题报告题目地址:https://leetcode.com/problems/two-sum-iv-input-is-a-bst/description/ 题目描述:   Given a Binary Search Tree and a target number, return true if th

郝春雨的博客 226

LeetCode 题解之 653. Two Sum IV - Input is a BST

653. Two Sum IV - Input is a BST 题目描述和难度 题目描述: 给定一个二叉搜索树和一个目标结果,如果 BST 中存在两个元素且它们的和等于给定的目标结果,则返回 true。 案例 1: 输入: 5 / \ 3 6 / \ \ 2 4 7 Target = 9 输出: True 案例 2: 输入...

李威威的博客 365

#力扣 LeetCode653. 两数之和 IV - 输入 BST @FDDLC

题目描述: https://leetcode-cn.com/problems/two-sum-iv-input-is-a-bst/ Java代码: class Solution { int[] a=new int[20000]; int p=0; public void inorder(TreeNode t){ if(t==null)return; inorder(t.left); a[p++]=t.val; .

LiuXingchang的博客 320

Leetcode653. Two Sum IV - Input is a BST

Given a Binary Search Tree and a target number, return true if there exist two elements in the BST such that their sum is equal to the given target.Example 1: Input: 5 / \ 3 6 / \ \

林剑的博客 328

LeetCode #653 Two Sum IV - Input is a BST

原题: Given a Binary Search Tree and a target number, return true if there exist two elements in the BST such that their sum is equal to the given target. Example 1: Input: 5

LLC71777的博客 290

LeetCode Two Sum IV - Input is a BST

原题链接在这里:https://leetcode.com/problems/two-sum-iv-input-is-a-bst/description/ 题目: Given a Binary Search Tree and a target number, return true if there exist two elements in the BST such that their su...

weixin_30325793的博客 60

LeetCode-Two Sum IV - Input is a BST

LeetCode Java Two Sum IV - Input is a BST

坟头草一米七五 266
上一篇: LeetCode算法题-Set Mismatch(Java实现)
下一篇: LeetCode算法题-Robot Return to Origin(Java实现)
程序员小川
博客等级 码龄10年 47粉丝 305原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值