-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathDay48.java
80 lines (62 loc) · 1.51 KB
/
Day48.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
/* Find a pair with given target in BST */
import java.util.ArrayList;
import java.util.List;
public class Day48 {
static class Node {
int data;
Node left, right;
public Node(int item) {
data = item;
left = right = null;
}
}// class Node
public static int isPairPresent(Node root, int target) {
if (root == null)
return 0;
List<Integer> inorder = new ArrayList<>();
inorderTraversal(root, inorder);
int left = 0;
int right = inorder.size() - 1;
while (left < right) {
int sum = inorder.get(left) + inorder.get(right);
if (sum == target)
return 1;
else if (sum < target)
left++;
else
right--;
}
return 0;
}// isPairPresent()
private static void inorderTraversal(Node root, List<Integer> inorder) {
if (root == null)
return;
inorderTraversal(root.left, inorder);
inorder.add(root.data);
inorderTraversal(root.right, inorder);
}// inorderTraversal()
public static void main(String[] args) {
// Create a BST
/*
5
/ \
3 7
/ \ / \
2 4 6 8
*/
Node root = new Node(5);
root.left = new Node(3);
root.right = new Node(7);
root.left.left = new Node(2);
root.left.right = new Node(4);
root.right.left = new Node(6);
root.right.right = new Node(8);
int target = 9;
int isPairPresent = isPairPresent(root, target);
if (isPairPresent == 1) {
System.out.println("There is a pair of nodes in the BST that sums up to " + target);
} else {
System.out.println("No such pair exists in the BST");
}
}
}