Guest User

Untitled

a guest
Oct 17th, 2017
99
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.26 KB | None | 0 0
  1. const countNodes = (root) => {
  2. if (!root) { return 0; }
  3. let cur = root;
  4. let stack = [];
  5. let count = 0;
  6. stack.push(cur);
  7. // Get total # of elements
  8. while (stack.length) {
  9. const cur = stack.pop();
  10. count++;
  11. if (cur.left) {
  12. stack.push(cur.left);
  13. }
  14. if (cur.right) {
  15. stack.push(cur.right);
  16. }
  17. }
  18.  
  19. return count;
  20. };
  21.  
  22.  
  23.  
  24. var kthSmallest = function(root, k) {
  25. // Constant space, recursive
  26. const countLeft = countNodes(root.left);
  27. if (countLeft >= k) {
  28. return kthSmallest(root.left, k);
  29. }
  30. if (k > countLeft + 1) {
  31. return kthSmallest(root.right, k - 1 - countLeft);
  32. }
  33.  
  34. return root.val;
  35.  
  36.  
  37. // Linear space, O(nlogn + n)
  38. // const stack = [];
  39. // const final = [];
  40. // stack.push(root);
  41. // while (stack.length) {
  42. // const cur = stack.pop();
  43. // final.push(cur.val);
  44. // if (cur.right) {
  45. // stack.push(cur.right);
  46. // }
  47. // if (cur.left) {
  48. // stack.push(cur.left);
  49. // }
  50. // }
  51.  
  52. // const sorted = final.sort((a, b) => {
  53. // return a - b;
  54. // });
  55.  
  56. // console.log('sorted is', sorted);
  57.  
  58. // return sorted[k - 1];
  59.  
  60. };
Add Comment
Please, Sign In to add comment