Guest User

Untitled

a guest
May 21st, 2018
71
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.21 KB | None | 0 0
  1. // A<->B<->C<->D<->E<->F<->A
  2.  
  3. // F
  4. // / \
  5. // B H
  6. // / \ /
  7. // A D G
  8. // / \
  9. // C E
  10.  
  11. // loop through all elems in tree in order
  12. // curr node (ex: c)
  13. // curr.left = prev
  14. // prev.right = curr
  15.  
  16. class BSTree {
  17. constructor(value) {
  18. this.value = value;
  19. this.left = null;
  20. this.right = null;
  21. }
  22.  
  23. convertBSTToLinkedList() {
  24. let left = this.left ? this.left.convertBSTToLinkedList() : null;
  25. let right = this.right ? this.right.convertBSTToLinkedList() : null;
  26. return this._connectLists(left, right); // return head of connected lists
  27. }
  28.  
  29. _connectLists(left, right) {
  30. let head = this;
  31. let tail = this;
  32. if (left) {
  33. // connect left LL to root, and move 'head' to start of left LL
  34. let leftTail = left.left || left;
  35. leftTail.right = this;
  36. this.left = leftTail;
  37. head = left;
  38. }
  39. if (right) {
  40. // connect root to right LL, and move 'tail' to end of right LL
  41. let rightTail = right.left || right;
  42. this.right = right;
  43. right.left = this;
  44. tail = rightTail;
  45. }
  46. // connect head and tail, then return head
  47. head.left = tail;
  48. tail.right = head;
  49. return head;
  50. }
  51. }
  52.  
  53. // TESTS ---------------------------------
  54.  
  55. // root node has no children
  56. let input = new BSTree("A");
  57. console.log(input.convertBSTToLinkedList()); // A<->A
  58.  
  59. // root node has some children, tree only goes 1 add'tl level
  60. input = new BSTree("B");
  61. input.left = new BSTree("A");
  62. input.right = new BSTree("C");
  63. console.log(input.convertBSTToLinkedList()); // A<->B<->C<->A
  64.  
  65. // larger test case, multiple levels
  66. input = new BSTree("F");
  67. input.left = new BSTree("B");
  68. input.left.left = new BSTree("A");
  69. input.left.right = new BSTree("D");
  70. input.left.right.left = new BSTree("C");
  71. input.left.right.right = new BSTree("E");
  72. input.right = new BSTree("H");
  73. input.right.left = new BSTree("G");
  74. console.log(input.convertBSTToLinkedList()); // A<->B<->C<->D<->E<->F<->G<->H<->A
  75.  
  76. // ARCHIVE -------------------------------
  77.  
  78. // old code from CodePad
  79. // let prev;
  80. // const traverseTree = node => {
  81. // if (!node) {
  82. // prev = node.value;
  83. // return;
  84. // }
  85. // traverseTree(node.left);
  86. // // handle curr node
  87. // traverseTree(node.right);
  88. // }
Add Comment
Please, Sign In to add comment