102. 二叉树的层序遍历
Posted cheshl
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了102. 二叉树的层序遍历相关的知识,希望对你有一定的参考价值。
/** * 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 MAXNODE 5000 struct TreeNode *treequeue[MAXNODE]; int** levelOrder(struct TreeNode* root, int* returnSize, int** returnColumnSizes){ *returnSize=0; if(root==NULL){ * returnSize=0; return NULL; } //二维数组分配内存 int **ret=(int **)malloc(sizeof(int *)*MAXNODE); //不能够申请这么大空间,后面使用的时候按照需要申请,否则容易超时 //for(int i=0;i<MAXNODE;i++){ // ret[i]=(int *)malloc(sizeof(int)*MAXNODE); //} //出参数分配内存 *returnColumnSizes = (int *)malloc(sizeof(int) * MAXNODE);//注意这块也要分配内存 int start=0; int end=0; treequeue[end++]=root; struct TreeNode *tmptree=NULL; while(start<end){ //当前层节点数 (* returnColumnSizes)[*returnSize]=end-start; // 此处已经有长度可以在这里进行申请内存,减少时间使用 ret[*returnSize] = (int *)malloc(sizeof(int) * (end-start)); for(int i=0;i<(*returnColumnSizes)[*returnSize];i++){ tmptree=treequeue[start]; ret[*returnSize][i]=tmptree->val; if(tmptree->left){ treequeue[end++]=tmptree->left; } if(tmptree->right){ treequeue[end++]=tmptree->right; } start++; } (*returnSize)++; } return ret; }
给你一个二叉树,请你返回其按 层序遍历 得到的节点值。 (即逐层地,从左到右访问所有节点)。
示例:
二叉树:[3,9,20,null,null,15,7]
,
3 / 9 20 / 15 7
返回其层次遍历结果:
[ [3], [9,20], [15,7] ]
总结:
C语言实现:栈和队列
102题:
优秀代码:
https://leetcode-cn.com/problems/binary-tree-level-order-traversal/solution/102-er-cha-shu-de-ceng-xu-bian-li-cyu-yan-bfs-by-x/
bfs:
https://leetcode-cn.com/problems/binary-tree-level-order-traversal/solution/cyu-yan-zhen-de-zao-bu-qi-lun-zi-liao-shun-xu-dui-/
https://leetcode-cn.com/problems/binary-tree-level-order-traversal/solution/cti-jie-bfs-shu-zu-mo-ni-dui-lie-by-justdoitno1/
https://leetcode-cn.com/problems/binary-tree-level-order-traversal/solution/xiao-hao-nei-cun-jiao-da-by-lang-dao/只实现初始化和pop push操作
https://leetcode-cn.com/problems/binary-tree-level-order-traversal/solution/c-yu-yan-4-ms-89-mb-by-chen-xiang-yin/使用大数组替代队列
申请空间数组
https://leetcode-cn.com/problems/binary-tree-level-order-traversal/solution/102-er-cha-shu-de-ceng-xu-bian-li-cyu-yan-bfs-by-x/
dfs:https://leetcode-cn.com/problems/binary-tree-level-order-traversal/solution/cyu-yan-shen-du-you-xian-sou-suo-by-jing-shui-li-2/
c语言实现队列:
https://mp.weixin.qq.com/s?src=11×tamp=1606011440&ver=2721&signature=OJj6qdyHzyY9zVf6zzunnMeLMkOo6RAGYzj8WbeigLasQUzmxOG*m13VqbB27cUFfta8SGzlbxCf6U7nxpYMy028qDJLemKXOfmKMyR*37IUkRXbNc45M1bJQ889BmVR&new=1
https://blog.csdn.net/weixin_41143631/article/details/81675177
C语言实现栈:
https://zhuanlan.zhihu.com/p/90582016
本体主要考察:
1、int** returnColumnSizes返回方式
2、bfs使用方法;
3、申请内存尽量按照需要使用否则容易出现超时
4、二维指针的返回值使用
5、dfs要使用stack,bfs要使用队列
以上是关于102. 二叉树的层序遍历的主要内容,如果未能解决你的问题,请参考以下文章