Created
March 11, 2018 21:06
-
-
Save vadimkorr/8da09bb4e05e9f34ba506cb5cad8283e to your computer and use it in GitHub Desktop.
Construct sorted linked list from binary search tree
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| let node = function(data) { | |
| this.data = data; | |
| this.left = null; | |
| this.right = null; | |
| } | |
| let head; | |
| let BT2DLL = function(root) | |
| { | |
| // Base cases | |
| if (!root) return; | |
| // Recursively convert right subtree | |
| BT2DLL(root.right); | |
| // insert root into DLL | |
| root.right = head; | |
| // Change left pointer of previous head | |
| if (head) head.left = root; | |
| // Change head of Doubly linked list | |
| head = root; | |
| // Recursively convert left subtree | |
| BT2DLL(root.left); | |
| } | |
| // Utility function for printing double linked list. | |
| let printDLL = function(head) | |
| { | |
| console.log('Print DLL'); | |
| while (head) | |
| { | |
| console.log(head.data); | |
| head = head.right; | |
| } | |
| } | |
| preOrder = function(node) { | |
| if (!node) return null; | |
| console.log(node.data); | |
| preOrder(node.left); | |
| preOrder(node.right); | |
| } | |
| // app | |
| let root = new node(5); | |
| root.left = new node(3); | |
| root.right = new node(6); | |
| root.left.left = new node(1); | |
| root.left.right = new node(4); | |
| root.right.right = new node(8); | |
| root.left.left.left = new node(0); | |
| root.left.left.right = new node(2); | |
| root.right.right.left = new node(7); | |
| root.right.right.right = new node(9); | |
| preOrder(root); | |
| BT2DLL(root); | |
| printDLL(head); | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment