题解 | #求二叉树的层序遍历#
求二叉树的层序遍历
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 ) { // write code here int** res = (int**)malloc(sizeof(int*) * 1500); if (root == NULL) { *returnSize = 0; return res; } *returnColumnSizes = (int*)malloc(sizeof(int) * 1500); struct TreeNode* queue[1501]; struct TreeNode* temp; int front = 0, rear = 0, i = 0; queue[rear++] = root; while (front < rear) { int last = rear; int j = 0; res[i] = (int*)malloc(sizeof(int) * 1500); while (front < last) { temp = queue[front++]; res[i][j++] = temp->val; if (temp->left) queue[rear++] = temp->left; if (temp->right) queue[rear++] = temp->right; } (*returnColumnSizes)[i] = j; i++; } *returnSize = i; return res; }