题解 | #按之字形顺序打印二叉树#

按之字形顺序打印二叉树

https://www.nowcoder.com/practice/91b69814117f4e8097390d107d2efbe0

/**
 * struct TreeNode {
 *  int val;
 *  struct TreeNode *left;
 *  struct TreeNode *right;
 * };
 */
/**
 * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
 *
 *
 * @param pRoot TreeNode类
 * @return int整型二维数组
 * @return int* returnSize 返回数组行数
 * @return int** returnColumnSizes 返回数组列数
 */
int** Print(struct TreeNode* root, int* returnSize, int** returnColumnSizes ) {
    // write code here
    int** res = (int**)malloc(sizeof(int*) * 1500);
    int* nums = (int*)malloc(sizeof(int) * 1500);
    if (root == NULL) {
        *returnSize = 0;
        return res;
    }
    *returnColumnSizes = (int*)malloc(sizeof(int) * 1500);
    struct TreeNode* queue[1500];
    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);
        memset(nums, 0, sizeof(int) * 1500);
        while (front < last) {
            temp = queue[front++];
            if (i % 2 != 0) nums[j++] = temp->val;
            if (i % 2 == 0) res[i][j++] = temp->val;
            if (temp->left) queue[rear++] = temp->left;
            if (temp->right) queue[rear++] = temp->right;
        }
        int p = 0;
        if (i % 2 != 0) {
            for (int k = j - 1; k >= 0; k--) {
                res[i][p++] = nums[k];
            }
        }
        (*returnColumnSizes)[i] = j;
        i++;
    }
    *returnSize = i;
    return res;
}

全部评论

相关推荐

10-24 11:10
山西大学 Java
若梦难了:哥们,面试挂是很正常的。我大中厂终面挂,加起来快10次了,继续努力吧。
点赞 评论 收藏
分享
我见java多妩媚:大外包
点赞 评论 收藏
分享
评论
点赞
收藏
分享
牛客网
牛客企业服务