Given the root of a binary tree, return the level order traversal of its nodes’ values. (i.e., from left to right, level by level).
Input: root = [3,9,20,null,null,15,7]
Output: [[3],[9,20],[15,7]]
Input: root = [1]
Output: [[1]]
Input: root = []
Output: []
From: LeetCode
Link: 102. Binary Tree Level Order Traversal
/**
* 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) {
if (!root) {
*returnSize = 0;
return NULL;
}
// Create a queue for BFS
struct TreeNode** queue = malloc(2000 * sizeof(struct TreeNode*));
int front = 0, rear = 0;
// Enqueue root
queue[rear++] = root;
int** result = malloc(2000 * sizeof(int*));
*returnColumnSizes = malloc(2000 * sizeof(int));
*returnSize = 0;
while (front < rear) {
// Number of nodes at current level
int levelSize = rear - front;
(*returnColumnSizes)[*returnSize] = levelSize;
// Allocate memory for nodes of this level
result[*returnSize] = malloc(levelSize * sizeof(int));
for (int i = 0; i < levelSize; i++) {
// Dequeue node
struct TreeNode* current = queue[front++];
// Add node's value to result
result[*returnSize][i] = current->val;
// Enqueue left child
if (current->left) {
queue[rear++] = current->left;
}
// Enqueue right child
if (current->right) {
queue[rear++] = current->right;
}
}
(*returnSize)++;
}
free(queue);
return result;
}