给你二叉树的根节点 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;
}