File tree Expand file tree Collapse file tree
Expand file tree Collapse file tree Original file line number Diff line number Diff line change @@ -32,15 +32,20 @@ public static void main(String[] args) {
3232 ArrayList <Node > dll = bstToDLL (root );
3333 printDll (dll );
3434
35+ bstToDll1 (root );
36+
37+ System .out .print (tail .value );
38+
3539 }
3640
3741
3842 public static void printDll (ArrayList <Node > dll ) {
3943 if (dll .size () != 0 ) {
40- for (Node n : dll ){
44+ for (Node n : dll ) {
4145 System .out .print (n .value + " " );
4246 }
4347 }
48+ System .out .println ();
4449 }
4550
4651 // not in place
@@ -52,15 +57,14 @@ public static ArrayList<Node> bstToDLL(Node node) {
5257 ArrayList <Node > dll = new ArrayList <Node >();
5358 Node current = node ;
5459 boolean done = false ;
55- while (!done ){
56- if (current != null ){
60+ while (!done ) {
61+ if (current != null ) {
5762 stack .push (current );
5863 current = current .left ;
59- }else {
60- if (stack .isEmpty ()){
64+ } else {
65+ if (stack .isEmpty ()) {
6166 done = true ;
62- }
63- else {
67+ } else {
6468 current = stack .pop ();
6569 dll .add (current );
6670 current = current .right ;
@@ -70,5 +74,35 @@ public static ArrayList<Node> bstToDLL(Node node) {
7074 return dll ;
7175 }
7276
77+ static Node prev , tail ;
78+
79+ public static void bstToDll1 (Node p ) {
80+ if (p == null )
81+ return ;
82+
83+ bstToDll1 (p .left );
84+ p .left = prev ;
85+ if (prev == null ){
86+ tail = p ;
87+ }
88+ else {
89+ // current node (smallest element) is head of
90+ // the list if previous node is not available
91+ prev .right = p ;
92+ }
93+
94+ // as soon as the recursion ends, the head's left pointer
95+ // points to the last node, and the last node's right pointer
96+ // points to the head pointer.
97+
98+ Node rightNode = p .right ;
99+ tail .left = p ;
100+ p .right = tail ;
101+ prev = p ;
102+
103+ bstToDll1 (rightNode );
104+
105+ }
106+
73107
74108}
You can’t perform that action at this time.
0 commit comments