题解 | #求二叉树的层序遍历#

求二叉树的层序遍历

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;

}

全部评论

相关推荐

把球:这个听过,你加了就会发现是字节的hr
点赞 评论 收藏
分享
评论
点赞
收藏
分享
牛客网
牛客企业服务