前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >二叉树层序遍历C语言版

二叉树层序遍历C语言版

作者头像
全栈程序员站长
发布2022-08-31 17:35:26
5000
发布2022-08-31 17:35:26
举报

大家好,又见面了,我是你们的朋友全栈君。

二叉树层序遍历C语言版

leetcode 102

代码语言:javascript
复制
/**
 * 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){
    * returnSize = 0;
    * returnColumnSizes = malloc(sizeof(int) * 2010);
    if(root == NULL){
        return 0;
    }
    int i = 0;
    struct TreeNode* node;
    int front=0, top = 0;
    struct TreeNode** q = malloc(sizeof(struct TreeNode*) * 2010);
    int** ret = malloc(sizeof(int*) * 2010);
    q[top++] = root; //q[0] = root
    // 队列为空 top==front
    while(top - front > 0){

        int q_size = top - front;
        (* returnColumnSizes)[i] = q_size;
        ret[i] = malloc(sizeof(int) * q_size);
        for(int j =0; j < q_size;j++){
            node = q[front++]; //出队
            ret[i][j] = node->val;   
            if(node->left != NULL)  q[top++]= node->left;     // push
            if(node->right != NULL)  q[top++]= node->right;
        }
        i++;
    }
    * returnSize = i;
    return ret;

}

挺有意思的

发布者:全栈程序员栈长,转载请注明出处:https://javaforall.cn/143573.html原文链接:https://javaforall.cn

本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2022年5月2,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 二叉树层序遍历C语言版
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档