【LeetCode】653. Two Sum IV
来源:互联网 发布:淘宝上买东西分期还 编辑:程序博客网 时间:2024/06/05 17:59
【题目】
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。时间复杂度为最坏为O(h2),最好为O(h),空间复杂度为O(n),n为节点个数。
【代码】
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */class Solution { public void middleTraversal(TreeNode root,List<Integer> nums){ if(null==root) return; middleTraversal(root.left,nums); nums.add(root.val); middleTraversal(root.right,nums); } public boolean findTarget(TreeNode root, int k) { //先中序遍历二叉搜索树,存到list中,然后从list中找 List<Integer> nums=new ArrayList<Integer>(); middleTraversal(root,nums); int len=nums.size(); int i=0,j=len-1; while(i<j){ if(nums.get(i)+nums.get(j)==k) return true; while(i<j && nums.get(i)+nums.get(j)<k) ++i; while(i<j && nums.get(i)+nums.get(j)>k) --j; } return false; }}
阅读全文
0 0
- 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[Two Sum IV
- LeetCode Two Sum IV
- leetcode Two Sum IV
- [Leetcode] Binary tree--653. Two Sum IV
- JavaScript知识点整理(2)
- 三种常见web攻击方式,xss、csrf和clickJacking
- HDOJ1083 匈牙利算法模板题
- 安装net.framework失败的4种解决方法,还在心烦的你确定不看看?
- 9.2NOIP模拟赛
- 【LeetCode】653. Two Sum IV
- c++基础之语句
- 【NOIP2012模拟8.9】监听还原
- java中main()方法里面的String[] args;String args[]
- JavaScript 的使用基础总结③
- Java NIO系列教程(十二) Java NIO与IO
- WebService开发(一)
- Codeforces 849C From Y to Y【思维】
- linux最小系统的制作(嵌入式第一节课)