111. 二叉树的最小深度

题目

给定一个二叉树,找出其最小深度。
最小深度是从根节点到最近叶子节点的最短路径上的节点数量。
说明:叶子节点是指没有子节点的节点。

解题思路

BFS广度优先算法
使用队列进行层序遍历,自上而下、逐层地探索树的结构。一旦发现第一个叶子节点,立即返回当前深度作为最小深度。

代码

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     struct TreeNode *left;
 *     struct TreeNode *right;
 * };
 */


/* BFS: 广度优先遍历 */
int minDepth(struct TreeNode* root) {
    /* 边界判断 */
    if (root == NULL) {
        return 0;
    }

    // 初始深度为1
    int depth = 1;

    /* 初始化队列 */
    struct TreeNode** queue =
        (struct TreeNode**)malloc(sizeof(struct TreeNode*) * 10000);
    int top = 0;
    int rear = 0;

    // 根节点入队
    queue[rear++] = root;

    while (top != rear) {
        // 获得当前队列长度(=当前遍历层节点个数)
        int count = rear - top;
        
        while (count > 0) {
            // 节点出队
            struct TreeNode* cur = queue[top++];
            count--;

            // 若节点非叶子节点:左右子树入队
            if (cur->left != NULL) {
                queue[rear++] = cur->left;
            }
            if (cur->right != NULL) {
                queue[rear++] = cur->right;
            }

            // 节点为叶子节点,直接返回
            if (cur->left == NULL && cur->right == NULL) {
                free(queue);
                return depth;
            }
        }

        // 当前层遍历结束,深度+1
        depth++;
    }
    free(queue);
    return depth;
}

改进代码

你可能感兴趣的:(111. 二叉树的最小深度)