csPost.js 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. import { csTdfs } from './csTdfs.js';
  2. /**
  3. * Post order a tree of forest
  4. *
  5. * @param {Array} parent The tree or forest
  6. * @param {Number} n Number of columns
  7. *
  8. * Reference: http://faculty.cse.tamu.edu/davis/publications.html
  9. */
  10. export function csPost(parent, n) {
  11. // check inputs
  12. if (!parent) {
  13. return null;
  14. }
  15. // vars
  16. var k = 0;
  17. var j;
  18. // allocate result
  19. var post = []; // (n)
  20. // workspace, head: first n entries, next: next n entries, stack: last n entries
  21. var w = []; // (3 * n)
  22. var head = 0;
  23. var next = n;
  24. var stack = 2 * n;
  25. // initialize workspace
  26. for (j = 0; j < n; j++) {
  27. // empty linked lists
  28. w[head + j] = -1;
  29. }
  30. // traverse nodes in reverse order
  31. for (j = n - 1; j >= 0; j--) {
  32. // check j is a root
  33. if (parent[j] === -1) {
  34. continue;
  35. }
  36. // add j to list of its parent
  37. w[next + j] = w[head + parent[j]];
  38. w[head + parent[j]] = j;
  39. }
  40. // loop nodes
  41. for (j = 0; j < n; j++) {
  42. // skip j if it is not a root
  43. if (parent[j] !== -1) {
  44. continue;
  45. }
  46. // depth-first search
  47. k = csTdfs(j, k, w, head, next, post, stack);
  48. }
  49. return post;
  50. }