Skip to content

Commit 0de7489

Browse files
Two Sum IV - Input is a BST : Accepted
1 parent 9e6ab3b commit 0de7489

File tree

2 files changed

+71
-0
lines changed

2 files changed

+71
-0
lines changed

README.md

+1
Original file line numberDiff line numberDiff line change
@@ -247,6 +247,7 @@ My accepted leetcode solutions to some of the common interview problems.
247247
- [Diameter of Binary Tree](problems/src/tree/DiameterOfBinaryTree.java) (Easy)
248248
- [Binary Tree Paths](problems/src/tree/BinaryTreePaths.java) (Easy)
249249
- [Sum of Left Leaves](problems/src/tree/SumofLeftLeaves.java) (Easy)
250+
- [Two Sum IV - Input is a BST](problems/src/tree/TwoSumIV.java) (Easy)
250251

251252
#### [Two Pointers](problems/src/two_pointers)
252253

problems/src/tree/TwoSumIV.java

+70
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,70 @@
1+
package tree;
2+
3+
import java.util.HashSet;
4+
5+
/**
6+
* Created by gouthamvidyapradhan on 16/12/2017.
7+
* Given a Binary Search Tree and a target number, return true if there exist two elements in the BST such that
8+
* their sum is equal to the given target.
9+
10+
Example 1:
11+
Input:
12+
5
13+
/ \
14+
3 6
15+
/ \ \
16+
2 4 7
17+
18+
Target = 9
19+
20+
Output: True
21+
Example 2:
22+
Input:
23+
5
24+
/ \
25+
3 6
26+
/ \ \
27+
2 4 7
28+
29+
Target = 28
30+
31+
Output: False
32+
*/
33+
public class TwoSumIV {
34+
35+
public class TreeNode {
36+
int val;
37+
TreeNode left;
38+
TreeNode right;
39+
TreeNode(int x) { val = x; }
40+
}
41+
42+
/**
43+
* Main method
44+
* @param args
45+
* @throws Exception
46+
*/
47+
public static void main(String[] args) throws Exception{
48+
}
49+
50+
public boolean findTarget(TreeNode root, int k) {
51+
return inorder(root, new HashSet<>(), k);
52+
}
53+
54+
private boolean inorder(TreeNode node, HashSet<Integer> set, int k){
55+
if(node != null){
56+
int req = k - (node.val);
57+
if(set.contains(req)){
58+
return true;
59+
}
60+
set.add(node.val);
61+
if(inorder(node.left, set, k)){
62+
return true;
63+
} else{
64+
if(inorder(node.right, set, k)){
65+
return true;
66+
}
67+
}
68+
} return false;
69+
}
70+
}

0 commit comments

Comments
 (0)