-
Notifications
You must be signed in to change notification settings - Fork 22
/
Copy pathDay_31_PairSumBST.java
56 lines (50 loc) · 1.6 KB
/
Day_31_PairSumBST.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
/*************************************************************
Following is the Binary Tree node structure:
class BinaryTreeNode {
int data;
BinaryTreeNode left;
BinaryTreeNode right;
BinaryTreeNode(int data) {
this.data = data;
left = null;
right = null;
}
}
*************************************************************/
// #M1 Using HashSet
import java.util.*;
public class Solution {
static HashSet<Integer> set=new HashSet<>();
public static boolean pairSum(BinaryTreeNode root, int k){
if(root==null) return false;
if(set.contains(k - root.data)) return true;
set.add(root.data);
return pairSum(root.left, k) || pairSum(root.right, k);
}
public static boolean pairSumBst(BinaryTreeNode root, int k) {
// Write your code here.
boolean res=pairSum(root, k);
set.clear();
return res;
}
}
// #M2 Using Binary Search
public class Solution {
public static boolean binarySearch(BinaryTreeNode root, BinaryTreeNode cur, int k){
while(root!=null){
if(root.data==k && root!=cur) return true;
else if(root.data>k) root=root.left;
else root=root.right;
}
return false;
}
public static boolean dfs(BinaryTreeNode root, BinaryTreeNode cur, int k){
if(cur==null) return false;
return (binarySearch(root, cur, k-cur.data) || dfs(root, cur.left, k) || dfs(root, cur.right, k));
}
public static boolean pairSumBst(BinaryTreeNode root, int k) {
// Write your code here.
if(root==null) return false;
return dfs(root, root, k);
}
}