LeetCode Easy653中两数之和输入为BST的示例分析
发表于:2025-11-07 作者:千家信息网编辑
千家信息网最后更新 2025年11月07日,LeetCode Easy653中两数之和输入为BST的示例分析,针对这个问题,这篇文章详细介绍了相对应的分析和解答,希望可以帮助更多想解决这个问题的小伙伴找到更简单易行的方法。Description
千家信息网最后更新 2025年11月07日LeetCode Easy653中两数之和输入为BST的示例分析
LeetCode Easy653中两数之和输入为BST的示例分析,针对这个问题,这篇文章详细介绍了相对应的分析和解答,希望可以帮助更多想解决这个问题的小伙伴找到更简单易行的方法。
Description
https://leetcode.com/problems/two-sum-iv-input-is-a-bst/
Given the root of a Binary Search Tree and a target number k, return true if there exist two elements in the BST such that their sum is equal to the given target.
Example 1:
Input: root = [5,3,6,2,4,null,7], k = 9Output: true
Example 2:
Input: root = [5,3,6,2,4,null,7], k = 28Output: false
Example 3:
Input: root = [2,1,3], k = 4Output: true
Example 4:
Input: root = [2,1,3], k = 1Output: false
Example 5:
Input: root = [2,1,3], k = 3 Output: true
Constraints:
The number of nodes in the tree is in the range $[1, 10^4]$.
$-10^4 <= Node.val <= 10^4$
rootis guaranteed to be a valid binary search tree.$-10^5 <= k <= 10^5$
Analysis
用两指针方法,一指针前序遍历,另一指针二分查找。
Submission
public class TwoSumIVInputIsABST { public boolean findTarget(TreeNode root, int k) { return traverse(root, root, k); } // 前序遍历 private boolean traverse(TreeNode node, TreeNode root, int k) { if (node == null) return false; // node.val恰好是k的一半时,根据BST特性,没必要找另一个节点 if (2 * node.val != k && findTarget2(root, k - node.val)) return true; return traverse(node.left, root, k) || traverse(node.right, root, k); } // 二分查找 private boolean findTarget2(TreeNode node, int targetValue) { if (node == null) return false; if (node.val == targetValue) return true; return findTarget2(targetValue < node.val ? node.left : node.right, targetValue); }}Test
import static org.junit.Assert.*;import org.junit.Test;import com.lun.util.BinaryTree;import com.lun.util.BinaryTree.TreeNode;public class TwoSumIVInputIsABSTTest { @Test public void test() { TwoSumIVInputIsABST obj = new TwoSumIVInputIsABST(); TreeNode root1 = BinaryTree.integers2BinaryTree(5, 3, 6, 2, 4, null, 7); assertTrue(obj.findTarget(root1, 9)); assertFalse(obj.findTarget(root1, 28)); TreeNode root2 = BinaryTree.integers2BinaryTree(2, 1, 3); assertTrue(obj.findTarget(root2, 4)); assertFalse(obj.findTarget(root2, 1)); assertTrue(obj.findTarget(root2, 3)); }}关于LeetCode Easy653中两数之和输入为BST的示例分析问题的解答就分享到这里了,希望以上内容可以对大家有一定的帮助,如果你还有很多疑惑没有解开,可以关注行业资讯频道了解更多相关知识。
分析
指针
问题
之和
示例
输入
方法
更多
帮助
解答
易行
必要
简单易行
内容
小伙
小伙伴
特性
知识
篇文章
节点
数据库的安全要保护哪些东西
数据库安全各自的含义是什么
生产安全数据库录入
数据库的安全性及管理
数据库安全策略包含哪些
海淀数据库安全审计系统
建立农村房屋安全信息数据库
易用的数据库客户端支持安全管理
连接数据库失败ssl安全错误
数据库的锁怎样保障安全
网络安全 培训心得体会
服务器上的光模块是多少g
彝文古籍数据库
金山区常规网络技术质量
数据库的字符格式默认是
rust租什么服务器
搜狐邮箱的服务器
装修公司数据库分类
读取数据库中的所有数据类型
软件开发工具的英文是
无线网络技术的应用领域英文
软件开发市场的环境分析
网络安全对师生的好处
苹果6允许微信使用数据库
湖南品质软件开发创意
济源软件开发销售电话
网络安全公司新闻稿
数据库连接需要open吗
关于网络安全方面的保证书
工业园区推广软件开发代理商
国外网络安全教授
邹平hr管理软件开发
内网服务器映射到公网安全不
设置网络安全系列
系统架构师软件开发教程
语音聊天软件开发询价
服务器上挂什么最赚钱
360网络安全协同产业园
网络安全宣传法视频下载
永劫无间服务器数据互通吗