leetcode 102-二叉树的层序遍历

给你二叉树的根节点 root ,返回其节点值的 层序遍历 。 (即逐层地,从左到右访问所有节点)。

示例 1:

输入:root = [3,9,20,null,null,15,7]
输出:[[3],[9,20],[15,7]]


示例 2:

输入:root = [1]
输出:[[1]]


示例 3:

输入:root = []
输出:[]

提示:

树中节点数目在范围 [0, 2000] 内
-1000 <= Node.val <= 1000

/**
 * 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().
 */
int** levelOrder(struct TreeNode* root, int* returnSize, int** returnColumnSizes){
    struct TreeNode* temp[2020];      //BFS使用的临时变量
    *returnSize = 0;
    if(root == NULL)    //此树为空
        return NULL;

    int** res = (int**)malloc(sizeof(int*) * 2000); //返回数组
    *returnColumnSizes = (int*)malloc(sizeof(int) * 2000);  //

    int hand = 0, tail = 0;     //BFS控制变量
    temp[hand++] = root;

    struct TreeNode* tmp = NULL;
    while(tail != hand){
        int colSize = 0,last = hand;
        res[*returnSize] = (int*)malloc(sizeof(int) * (last - tail));

        while(tail < last){
            tmp = temp[tail]->left;//若存在左子树则为左子树地址,否则为NULL
            res[*returnSize][colSize++] = temp[tail]->val;
            if(tmp){
                temp[hand++] = temp[tail]->left;
            }

            tmp = temp[tail]->right;//若存在左子树则为左子树地址,否则为NULL
            if(tmp){
                temp[hand++] = temp[tail]->right;
            }  
            tail++;
        }
        (*returnColumnSizes)[*returnSize] = colSize;
        (*returnSize)++;
    }
    return res;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值