csTdfs.js 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. "use strict";
  2. Object.defineProperty(exports, "__esModule", {
  3. value: true
  4. });
  5. exports.csTdfs = csTdfs;
  6. /**
  7. * Depth-first search and postorder of a tree rooted at node j
  8. *
  9. * @param {Number} j The tree node
  10. * @param {Number} k
  11. * @param {Array} w The workspace array
  12. * @param {Number} head The index offset within the workspace for the head array
  13. * @param {Number} next The index offset within the workspace for the next array
  14. * @param {Array} post The post ordering array
  15. * @param {Number} stack The index offset within the workspace for the stack array
  16. *
  17. * Reference: http://faculty.cse.tamu.edu/davis/publications.html
  18. */
  19. function csTdfs(j, k, w, head, next, post, stack) {
  20. // variables
  21. var top = 0;
  22. // place j on the stack
  23. w[stack] = j;
  24. // while (stack is not empty)
  25. while (top >= 0) {
  26. // p = top of stack
  27. var p = w[stack + top];
  28. // i = youngest child of p
  29. var i = w[head + p];
  30. if (i === -1) {
  31. // p has no unordered children left
  32. top--;
  33. // node p is the kth postordered node
  34. post[k++] = p;
  35. } else {
  36. // remove i from children of p
  37. w[head + p] = w[next + i];
  38. // increment top
  39. ++top;
  40. // start dfs on child node i
  41. w[stack + top] = i;
  42. }
  43. }
  44. return k;
  45. }