leetcode简单题107.二叉树层次遍历 || (C)

题目概述:

给定一个二叉树,返回其节点值自底向上的层次遍历。 (即按从叶子节点所在层到根节点所在的层,逐层从左向右遍历)

例如:
给定二叉树 [3,9,20,null,null,15,7],

    3
   / \
  9  20
    /  \
   15   7

返回其自底向上的层次遍历为:

[
  [15,7],
  [9,20],
  [3]
]

 

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     struct TreeNode *left;
 *     struct TreeNode *right;
 * };
 */


/**
 * Return an array of arrays of size *returnSize.
 * The sizes of the arrays are returned as *returnColumnSizes array.
 * Note: Both returned array and *columnSizes array must be malloced, assume caller calls free().
 */
// 层次遍历后逆序遍历数组
// 难点是二维数组的

#define maxSize 1010 

int** levelOrderBottom(struct TreeNode* root, int* returnSize, int** returnColumnSizes){
    int front,rear;
    front = rear = 0;
    struct TreeNode* que[maxSize]; //定义循环队列
    int** res = (int**)malloc(sizeof(int*)*maxSize); //返回为一个二维数组
    *returnSize = 0; //其实是二维数组的行数
    *returnColumnSizes = (int*)malloc(sizeof(int)*maxSize); 
                     //二维数组存的是res的各行元素个数
    if(root)
    {
        rear = (rear+1)%maxSize;
        que[rear] = root;//根节点入队
    }
    while(front != rear)//队列不为空则一直循环
    {
        (*returnColumnSizes)[*returnSize] = rear - front;
        res[*returnSize] = (int*)malloc(sizeof(int)*(*returnColumnSizes)[*returnSize]);
        for(int i=0; i<(*returnColumnSizes)[*returnSize]; ++i)//对每一层的遍历
        {
            front = (front+1)%maxSize;
            struct TreeNode* cur = que[front];
            res[*returnSize][i] =cur->val;
            if(cur->left){
                rear = (rear+1)%maxSize;
                que[rear] = cur->left;
            }
            if(cur->right){
                rear = (rear+1)%maxSize;
                que[rear] = cur->right;
            }
        }
        (*returnSize)++; 
    }

    int i = 0, j = *returnSize - 1;
    while(i

 

你可能感兴趣的:(leetcode简单题107.二叉树层次遍历 || (C))