LeetCode //C - 102. Binary Tree Level Order Traversal

102. Binary Tree Level Order Traversal

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).

Example 1:

Input: root = [3,9,20,null,null,15,7]
Output: [[3],[9,20],[15,7]]

Example 2:

Input: root = [1]
Output: [[1]]

Example 3:

Input: root = []
Output: []

Constraints:

  • The number of nodes in the tree is in the range [0, 2000].
  • -1000 <= Node.val <= 1000

From: LeetCode

Link: 102. Binary Tree Level Order Traversal


Solution:

Ideas:
  1. Create a queue to hold the nodes of the tree.
  2. Enqueue the root node to the queue.
  3. While the queue is not empty:
  • Calculate the number of nodes at the current level.
  • Allocate memory for these nodes.
  • For each node at the current level:
    • Dequeue the node from the queue.
    • Add the node's value to the result.
    • Enqueue the node's left child (if it exists).
    • Enqueue the node's right child (if it exists).
  1. Return the result.
Code:
c 复制代码
/**
 * 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;
}
相关推荐
灰灰老师1 小时前
数据分析系列--[11] RapidMiner,K-Means聚类分析(含数据集)
人工智能·算法·机器学习·数据挖掘·数据分析·kmeans·rapidminer
追求源于热爱!2 小时前
记4(可训练对象+自动求导机制+波士顿房价回归预测
图像处理·人工智能·算法·机器学习·回归
qq_433618442 小时前
哈夫曼树
数据结构·算法
Icomi_2 小时前
【PyTorch】7.自动微分模块:开启神经网络 “进化之门” 的魔法钥匙
c语言·c++·人工智能·pytorch·python·机器学习·计算机视觉
余辉zmh2 小时前
【贪心算法篇】:“贪心”之旅--算法练习题中的智慧与策略(二)
c++·算法·leetcode·贪心算法
余辉zmh2 小时前
【贪心算法篇】:“贪心”之旅--算法练习题中的智慧与策略(一)
c++·算法·leetcode·贪心算法
ElvInR3 小时前
【C语言】动态内存管理
c语言·开发语言
taoyong0013 小时前
代码随想录算法训练营第三十七天-动态规划-完全背包-377. 组合总和 Ⅳ
c++·算法·leetcode·动态规划
励志成为美貌才华为一体的女子3 小时前
python算法和数据结构刷题[4]:查找算法和排序算法
数据结构·算法·排序算法
tt5555555555554 小时前
每日一题-判断是不是完全二叉树
数据结构·算法