给你一个二叉树,请你返回其按 层序遍历 得到的节点值。 (即逐层地,从左到右访问所有节点)。
示例:
二叉树:[3,9,20,null,null,15,7],
3
/ \
9 20
/ \
15 7
返回其层次遍历结果:
[
[3],
[9,20],
[15,7]
]
思路:利用队列的先进先出的规则,让每一层的节点先进入,然后要出队时,再把他的左右节点加入队列的末尾,以此类推。
/**
* 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 10000
int** levelOrder(struct TreeNode* root, int* returnSize, int** returnColumnSizes){
if(root == NULL) {
*returnSize = 0;
return;
}
int **result = (int**)malloc(sizeof(int*)*MAXSIZE);
*returnColumnSizes = (int*)malloc(sizeof(int)*MAXSIZE);
struct TreeNode* queen[10000];
int front = -1,rear = -1;
queen[++rear] = root;
int level = 0,n = 0;
while(front != rear){
n = (rear - front) % MAXSIZE;
result[level] = (int*)malloc(sizeof(int) * n);
struct TreeNode* p = queen[++front];
for(int i = 0;i < n;i++){
result[level][i] = p->val;
if(p->left != NULL){
queen[++rear] = p->left;
}
if(p->right!= NULL){
queen[++rear] = p->right;
}
}
level++;
}
*returnSize = level;
return result;
}