LeetCode Two Sum IV
来源:互联网 发布:红外图谱数据库 编辑:程序博客网 时间:2024/05/21 17:31
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 / \ \2 4 7Target = 9Output: True
Example 2:
Input: 5 / \ 3 6 / \ \2 4 7Target = 28Output: False
题解:此题要求在一棵二叉排序树中,寻找任意的两个节点的和等于给定的某个target值,如果存在这两个数的和为target,那么就输出true;否则就输出为false。此题我考虑先按照中序遍历,也就是左-根-右的顺序对一棵二叉树进行扫描,得到的是一串按照从小到大排列的数据,然后再根据从开始的节点和末尾的节点的和,再两两夹逼来寻找是否这两个数的和满足给定的这个target值。
public class findTarget{ public boolean findTarget(TreeNode root,int k) { ArrayList<Integer> list = new ArrayList<>(); inOrder(root,list); for(int i = 0,j = list.size() - 1 ; i < j;) //根据首尾进行相加来夹逼,得到和是否为target值。 { if((list.get(i) + list.get(j)) == k) return true; else if(list.get(i) + list.get(j) < k) i++; else j--; } return false; } public void inOrder(TreeNode root,ArrayList<Integer> list) //递归方式来对一棵二叉树进行中序遍历 { if(root == null) return; if(root.left != null) inOrder(root.left,list); list.add(root.val); if(root.right != null) inOrder(root.right,list); }}
阅读全文
0 0
- leetcode[Two Sum IV
- LeetCode Two Sum IV
- leetcode Two Sum IV
- leetcode 653. Two Sum IV
- Leetcode 653. Two Sum IV
- 【LeetCode】653. Two Sum IV
- Leetcode 653. Two Sum IV
- 【LeetCode】653. Two Sum IV
- leetcode 653. Two Sum IV
- leetcode 653. Two Sum IV
- [LeetCode]653. Two Sum IV
- leetcode: 653. Two Sum IV
- leetcode 653. Two Sum IV
- LeetCode 653. Two Sum IV
- LeetCode-653. Two Sum IV
- leetcode 653. Two Sum IV
- leetcode 653. Two Sum IV
- LeetCode #653 Two Sum IV
- 【leetcode】563. Binary Tree Tilt总结
- GCC编译程序出现 undefined reference to `std::ios_base::Init::Init()'问题
- 关于服务发现、Feign、Zuul 以及docker之间的依赖
- Eclipse配置hadoop环境
- 聊天-one
- LeetCode Two Sum IV
- 拷贝构造函数和无参构造函数,深浅拷贝
- Struts 从一个Action跳转到另一个action时xml的配置方式
- noip冲刺 持续更新
- SolrCloud的分布式实现
- c语言文件输入输出
- 优先队列详解(转载)
- kettle之定时抓取服务器上日志文件然后以附件形式送邮件
- 多因子模型之因子(信号)测试平台----alphalens(一)