File tree Expand file tree Collapse file tree 1 file changed +86
-0
lines changed Expand file tree Collapse file tree 1 file changed +86
-0
lines changed Original file line number Diff line number Diff line change
1
+ import java.util.*;
2
+ public class Solution {
3
+ /*
4
+ * BinaryTreeNode class
5
+ *
6
+ * class BinaryTreeNode<T>
7
+ * {
8
+ * T data;
9
+ * BinaryTreeNode<T> left;
10
+ * BinaryTreeNode<T> right;
11
+ * public BinaryTreeNode(T data)
12
+ * {
13
+ * this.data = data;
14
+ * }
15
+ * }
16
+ */
17
+
18
+ public static void printNodesSumToS(BinaryTreeNode<Integer> root, int s) {
19
+ // Write your code here
20
+ if (root==null)
21
+ return;
22
+ else
23
+ {
24
+ ArrayList<Integer> arr = convertToArray(root);
25
+ Collections.sort(arr);
26
+ //for (int i=0;i<arr.size();i++)
27
+ //{
28
+ // System.out.print (arr.get(i)+" ");
29
+ //}
30
+ //System.out.println();
31
+ printPairSum(arr,s);
32
+ }
33
+
34
+ }
35
+
36
+ private static ArrayList<Integer> convertToArray(BinaryTreeNode<Integer> root)
37
+ {
38
+ if (root==null)
39
+ {
40
+ ArrayList<Integer> arr = new ArrayList<Integer>();
41
+ return arr;
42
+ }
43
+
44
+
45
+ ArrayList<Integer> currArr = new ArrayList<Integer>();
46
+ ArrayList<Integer> leftArr = convertToArray(root.left);
47
+ if (!leftArr.isEmpty())
48
+ {
49
+ currArr.addAll(leftArr);
50
+ }
51
+
52
+ currArr.add(root.data);
53
+
54
+ ArrayList<Integer> rightArr = convertToArray(root.right);
55
+ if (!rightArr.isEmpty())
56
+ {
57
+ currArr.addAll(rightArr);
58
+ }
59
+ return currArr;
60
+ }
61
+
62
+ private static void printPairSum(ArrayList<Integer> arr, int s)
63
+ {
64
+ int i=0,j=arr.size()-1;
65
+ while(i<j)
66
+ {
67
+ int val1=arr.get(i);
68
+ int val2=arr.get(j);
69
+ if (val1+val2>s)
70
+ {
71
+ j=j-1;
72
+ }
73
+ else if(val1+val2<s)
74
+ {
75
+ i=i+1;
76
+ }
77
+ else
78
+ {
79
+ System.out.println(val1+" "+val2);
80
+ i=i+1;
81
+ j=j-1;
82
+ }
83
+
84
+ }
85
+ }
86
+ }
You can’t perform that action at this time.
0 commit comments