-
Notifications
You must be signed in to change notification settings - Fork 10
/
Copy pathBinary Tree to Binary Search Tree Conversion.java
72 lines (68 loc) · 1.58 KB
/
Binary Tree to Binary Search Tree Conversion.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
import java.lang.*;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
// You can improve the time complexity of the code using sets instead of sorting
class Node{
Node left;
Node right;
int data;
Node(int data){
this.data=data;
left=null;
right=null;
}
}
class Solution
{
List<Integer> list;
class ptr{
int val;
}
Node binaryTreeToBST(Node root)
{
list=new ArrayList<>();
dfs(root);
int[]array=new int[list.size()];
for(int i=0;i<list.size();i++){
array[i]=list.get(i);
}
Arrays.sort(array);
ptr ptr=new ptr();
ptr.val=0;
provider(root,array,ptr);
return root;
}
void provider(Node n,int[]array,ptr ptr){
if(n.left!=null){
provider(n.left,array,ptr);
}
n.data=array[ptr.val];
ptr.val++;
if(n.right!=null){
provider(n.right,array,ptr);
}
}
void dfs(Node n){
if(n.left!=null){dfs(n.left);}
list.add(n.data);
if(n.right!=null){dfs(n.right);}
}
}
class Implementation {
static void dfs(Node n){
if(n.left!=null){dfs(n.left);}
System.out.print(n.data+" ");
if(n.right!=null){dfs(n.right);}
}
public static void main (String[] args){
int[]a={10,5,1,7,20,40,50};
Node n=new Node(1);
n.left=new Node(2);
n.left.left=new Node(4);
n.right=new Node(3);
Solution s=new Solution();
n=s.binaryTreeToBST(n);
dfs(n);
}
}