题解 | #求二叉树的层序遍历#
求二叉树的层序遍历
https://www.nowcoder.com/practice/04a5560e43e24e9db4595865dc9c63a3
/** * struct TreeNode { * int val; * struct TreeNode *left; * struct TreeNode *right; * }; */ /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * * @param root TreeNode类 * @return int整型二维数组 * @return int* returnSize 返回数组行数 * @return int** returnColumnSizes 返回数组列数 */ int** levelOrder(struct TreeNode* root, int* returnSize, int** returnColumnSizes) { *returnSize = 0; if (!root) return NULL; int** res = (int**)malloc(sizeof(int*) * 1500); struct TreeNode* que[1500]; int head = 0; int rear = 0; que[rear++] = root; *returnColumnSizes = (int*)malloc(sizeof(int) * 1500); while (head != rear) { struct TreeNode* tmp; int prerear = rear; res[*returnSize] = (int*)malloc(sizeof(int) * (rear - head)); int k = 0; while (head != prerear) { tmp = que[head++]; res[(*returnSize)][k++] = tmp->val; if (tmp->left) que[rear++] = tmp->left; if (tmp->right) que[rear++] = tmp->right; } (*returnColumnSizes)[*returnSize] = k; (*returnSize)++; } return res; }