429.h 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. //
  2. // Created by 李洋 on 2024/2/17.
  3. //
  4. #ifndef LEETCODE_C_429_H
  5. #define LEETCODE_C_429_H
  6. #include "stdlib.h"
  7. struct Node {
  8. int val;
  9. int numChildren;
  10. struct Node **children;
  11. };
  12. struct linkedNode {
  13. int val;
  14. struct linkedNode *next;
  15. };
  16. struct queue {
  17. struct linkedNode *head;
  18. struct linkedNode *tail;
  19. int size;
  20. };
  21. void push(struct queue Q, int val) {
  22. struct linkedNode *temp = (struct linkedNode *) malloc(sizeof(struct linkedNode));
  23. Q.size++;
  24. if (Q.size == 0) {
  25. temp->val = val;
  26. Q.head = temp;
  27. Q.tail = temp;
  28. return;
  29. }
  30. Q.tail->next = temp;
  31. Q.tail = temp;
  32. }
  33. int pop(struct queue Q) {
  34. int top = Q.head->val;
  35. struct linkedNode *temp = Q.head;
  36. Q.head = temp->next;
  37. free(temp);
  38. Q.size--;
  39. return top;
  40. }
  41. int top(struct queue Q) {
  42. return Q.head->val;
  43. }
  44. int **levelOrder(struct Node *root, int *returnSize, int **returnColumnSizes) {
  45. int ** ans = (int **)malloc(sizeof(int *) * 1000);
  46. *returnColumnSizes = (int *)malloc(sizeof(int) * 1000);
  47. if (!root) {
  48. *returnSize = 0;
  49. return ans;
  50. }
  51. struct Node ** queue = (struct Node **)malloc(sizeof(struct Node *) * 10000);
  52. int head = 0, tail = 0;
  53. int level = 0;
  54. queue[tail++] = root;
  55. while (head != tail) {
  56. int cnt = tail - head;
  57. ans[level] = (int *)malloc(sizeof(int) * cnt);
  58. for (int i = 0; i < cnt; ++i) {
  59. struct Node * cur = queue[head++];
  60. ans[level][i] = cur->val;
  61. for (int j = 0; j < cur->numChildren; j++) {
  62. queue[tail++] = cur->children[j];
  63. }
  64. }
  65. (*returnColumnSizes)[level++] = cnt;
  66. }
  67. *returnSize = level;
  68. free(queue);
  69. return ans;
  70. }
  71. #endif //LEETCODE_C_429_H
备用站点 当前处于降级运行的备用站点,仅供应急访问,数据和功能可能不是最新。