forked from prateekshyap/DSA
-
Notifications
You must be signed in to change notification settings - Fork 0
/
FindPairInBST.java
103 lines (85 loc) · 2.35 KB
/
FindPairInBST.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
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
/*https://practice.geeksforgeeks.org/problems/find-a-pair-with-given-target-in-bst/1*/
//hashing technique - O(n) extra space
class Solution
{
HashMap<Integer, Integer> map;
int retVal = 0;
public int isPairPresent(Node root, int target)
{
map = new HashMap<Integer, Integer>();
//recursion call
inOrder(root, target);
return retVal;
}
public void inOrder(Node root, int sum)
{
if (root != null)
{
/*recursion*/
inOrder(root.left, sum);
//if the hashmap contains the other value
if (map.containsKey(sum-root.data))
{
//mark it and return
retVal = 1;
return;
}
//put the current value in hashmap
map.put(root.data,1);
/*recursion*/
inOrder(root.right, sum);
}
}
}
//two pointer approach after converting into a sorted DLL - O(h) extra space
class Solution
{
public Node head, tail;
void addNodeToRight(int num)
{
//create a new node after tail
tail.right = new Node(num);
//set the previous pointer of the new node
tail.right.left = tail;
//move tail
tail = tail.right;
}
void inOrder(Node root)
{
//if root is not null
if (root != null)
{
/*recursion*/
inOrder(root.left);
//add the current node to the end of the linked list
addNodeToRight(root.data);
/*recursion*/
inOrder(root.right);
}
}
public int isPairPresent(Node root, int target)
{
//initialize a dummy node and make both the pointers point to it
head = new Node(0);
tail = head;
//recursion call
inOrder(root);
//delete the dummy node
head = head.right;
head.left = null;
//two pointer approach to get the pair
Node left = head;
Node right = tail;
//till the pointers collide
while (left != right)
{
//if sum is equal to target return 1
if (left.data+right.data == target) return 1;
//if sum is less, move left pointer
else if (left.data+right.data < target) left = left.right;
//else move right pointer
else right = right.left;
}
return 0;
}
}