-
Notifications
You must be signed in to change notification settings - Fork 116
/
Copy pathBinary Search Trees:BST to Sorted LL
75 lines (66 loc) · 1.64 KB
/
Binary Search Trees:BST to Sorted LL
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
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;
}
}
*/
/* LinkedList Node Class
*
*
class LinkedListNode<T> {
T data;
LinkedListNode<T> next;
public LinkedListNode(T data) {
this.data = data;
}
}
*/
public static LinkedListNode<Integer> BSTToSortedLL(BinaryTreeNode<Integer> root){
/* 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.
*/
Pair ans=helper(root);
return ans.head;}
public static Pair helper(BinaryTreeNode<Integer> root){
if(root==null)
{
Pair output=new Pair();
output.head=null;
output.tail=null;
return output;
}
Pair lefttree=helper(root.left);
LinkedListNode<Integer> newNode=new LinkedListNode<>(root.data);
Pair righttree=helper(root.right);
Pair output=new Pair();
if(lefttree.head!=null)
{
output.head=lefttree.head;
lefttree.tail.next=newNode;
}
else {
output.head=newNode;
}
newNode.next=righttree.head;
if(righttree.head==null)
{
output.tail=newNode;
}
else{
output.tail=righttree.tail;
}
return output;
}}
class Pair{
LinkedListNode<Integer> head;
LinkedListNode<Integer> tail;
}