File tree Expand file tree Collapse file tree 1 file changed +51
-2
lines changed
src/me/ramswaroop/linkedlists Expand file tree Collapse file tree 1 file changed +51
-2
lines changed Original file line number Diff line number Diff line change 11package me .ramswaroop .linkedlists ;
22
3+ import me .ramswaroop .common .DoubleLinkedList ;
4+ import me .ramswaroop .common .DoubleLinkedNode ;
5+
36/**
47 * Created by IntelliJ IDEA.
58 *
912 */
1013public class SortedSLLToBBST {
1114
12- public void SortedSLLToBBST () {
15+ static <E extends Comparable <E >> int getLength (DoubleLinkedNode <E > node ) {
16+ int l = 0 ;
17+ DoubleLinkedNode <E > curr = node ;
18+ while (curr != null ) {
19+ curr = curr .next ;
20+ l ++;
21+ }
22+ return l ;
23+ }
1324
25+ static <E extends Comparable <E >> void inOrder (DoubleLinkedNode <E > node ) {
26+ if (node == null ) return ;
27+ inOrder (node .prev );
28+ System .out .print (node .item .toString ());
29+ inOrder (node .next );
1430 }
1531
16- public static void main (String a []) {
32+ public static <E extends Comparable <E >> DoubleLinkedNode <E > sortedSLLToBBST (DoubleLinkedNode <E > node ) {
33+ return sortedSLLToBBST (node , getLength (node ));
34+ }
35+
36+ public static <E extends Comparable <E >> DoubleLinkedNode <E > sortedSLLToBBST (DoubleLinkedNode <E > node , int n ) {
37+ if (n <= 0 ) {
38+ return null ;
39+ }
40+
41+ DoubleLinkedNode <E > left = sortedSLLToBBST (node , n / 2 );
1742
43+ DoubleLinkedNode <E > root = node ;
44+ root .prev = left ;
45+
46+ node = node .next ;
47+
48+ DoubleLinkedNode <E > right = sortedSLLToBBST (node , n - n / 2 - 1 );
49+ root .next = right ;
50+
51+ return root ;
52+ }
53+
54+ public static void main (String a []) {
55+ DoubleLinkedList <Integer > linkedList = new DoubleLinkedList <>();
56+ linkedList .add (11 );
57+ linkedList .add (22 );
58+ linkedList .add (33 );
59+ linkedList .add (44 );
60+ linkedList .add (55 );
61+ linkedList .add (66 );
62+ linkedList .add (77 );
63+ linkedList .printList ();
64+ inOrder (sortedSLLToBBST (linkedList .head ));
65+ System .out .println ();
66+ linkedList .printList ();
1867 }
1968}
You can’t perform that action at this time.
0 commit comments