-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathBinary Search Trees:Pair sum BInary Tree
104 lines (93 loc) · 3.07 KB
/
Binary Search Trees:Pair sum BInary Tree
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
104
import java.util.Arrays;
public class Solution {
/* Binary Tree Node class
*
* class BinaryTreeNode<T> {
T data;
BinaryTreeNode<T> left;
BinaryTreeNode<T> right;
public BinaryTreeNode(T data) {
this.data = data;
}
}
*/
// public static void nodesSumToS(BinaryTreeNode<Integer> root, int sum) {
// // Write your code here
// // final BinaryTreeNode<Integer> a =root;
// if(root==null)
// return;
// if(root.data<sum)
// {int diff=sum-root.data;
// // search for difference==========
// boolean findNode=isNodePresent(a,diff);
// if(findNode){
// if(root.data<diff)
// System.out.println(root.data+" "+diff);
// else
// System.out.println(diff+" "+root.data);
// }}
// else{
// nodesSumToS(root.left,sum);
// nodesSumToS(root.right,sum);
// }
// }
// public static boolean isNodePresent(BinaryTreeNode<Integer> root,int x){
// /* Your class should be named Solution
// * Don't write main().
// * Don't read input, it is passed as function argument.
// * Return output and don't print it.
// * Taking input and printing output is handled automatically.
// */
// if(root==null)
// return false;
// boolean ans=false;
// if(root.data.equals(x))
// return true;
// ans=isNodePresent(root.left,x);
// if(ans==true)
// return true;
// ans=isNodePresent(root.right,x);
// if (ans==true)
// return true;
// return ans;}
public static void nodesSumToS(BinaryTreeNode<Integer> root, int sum) {
if(root==null)
return;
int[] arr=arrayInsertion(root);
Arrays.sort(arr);
int i=0;
int j=arr.length-1;
while(i<j){
if(arr[i]+arr[j]==sum){
System.out.println(arr[i]+" "+arr[j]);
i++;
j--;}
else if(arr[i]+arr[j]<sum)
i++;
else
j--;
}
}
private static int[] arrayInsertion(BinaryTreeNode<Integer> root){
if(root==null){
int[] arr=new int[0];
return arr;}
int firstData=root.data;
int[] jrr= arrayInsertion(root.left);
int[] krr= arrayInsertion(root.right);
int[] finalArray=new int[1+jrr.length+krr.length];
int k=0;
finalArray[k]=firstData;
k++;
for(int i=0;i<jrr.length;i++)
{ finalArray[k]=jrr[i];
k++;
}
for(int i=0;i<krr.length;i++)
{
finalArray[k]=krr[i];
k++;
}
return finalArray;
}
}