二叉树层序遍历C语言版
leetcode 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().
*/
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;
}
挺有意思的