Skip to content

Commit

Permalink
Create flattenLLJava
Browse files Browse the repository at this point in the history
  • Loading branch information
striver79 authored Oct 1, 2021
1 parent 4244cd2 commit 2877cd8
Showing 1 changed file with 39 additions and 0 deletions.
39 changes: 39 additions & 0 deletions flattenLLJava
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
Node mergeTwoLists(Node a, Node b) {

Node temp = new Node(0);
Node res = temp;

while(a != null && b != null) {
if(a.data < b.data) {
temp.bottom = a;
temp = temp.bottom;
a = a.bottom;
}
else {
temp.bottom = b;
temp = temp.bottom;
b = b.bottom;
}
}

if(a != null) temp.bottom = a;
else temp.bottom = b;
return res.bottom;

}
Node flatten(Node root)
{

if (root == null || root.next == null)
return root;

// recur for list on right
root.next = flatten(root.next);

// now merge
root = mergeTwoLists(root, root.next);

// return the root
// it will be in turn merged with its left
return root;
}

0 comments on commit 2877cd8

Please sign in to comment.