leetcode——第111题——二叉树的最小深度

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

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
public:
// /************************法一::递归法**********************/
//     int depth(TreeNode* cur)
//     {
//         if(cur == nullptr)
//         {
//             return 0;
//         }
//   /*这里这么写是错误的,因为这样会把没有左孩子的分子算为最短分支
//     或者是把没有右孩子的分支算为最短分支

//         int leftDepth = depth(cur->left);
//         int rightDepth = depth(cur->right);
//         return (min(leftDepth,rightDepth)+1);
        
//     所以,正确的逻辑应该为:
//     1)如果左子树为空,右子树不为空,说明最小深度是 1 + 右子树的深度。
//     2)右子树为空,左子树不为空,最小深度是 1 + 左子树的深度。
//     3)最后如果左右子树都不为空,返回左右子树深度最小值 + 1 。      

//     左右子树都为空的话,就相当于 cur == nullptr 
//         */
//         int leftDepth = depth(cur->left);
//         int rightDepth = depth(cur->right);
//         if(cur->left == nullptr && cur->right != nullptr)
//         {
//             return 1+rightDepth;
//         }
//         if(cur->left  != nullptr && cur->right == nullptr)
//         {
//             return 1+leftDepth;
//         }
//         return 1+min(rightDepth,leftDepth);
//     }
//     int minDepth(TreeNode* root) 
//     {
//         return depth(root);
//     }

/************************法二::迭代法**********************/
    int minDepth(TreeNode* root) 
    {
        queue<TreeNode*> que;
        if(root != nullptr)  que.push(root);
        int minDepth = 0;
        while(!que.empty())
        {
            int size = que.size();
            int flag = 0;
            minDepth++;
            for(int i=0; i<size; i++)
            {
                TreeNode* node = que.front();
                que.pop();

                if(node->left != nullptr)   que.push(node->left);
                if(node->right != nullptr)  que.push(node->right);
                // 接来下这里确实不太好想明白,请仔细想想 plz
                // 当左右孩子都为空时,说明是到最低的一层了,就退出 两层 两层 循环。
                if(node->left == nullptr && node->right == nullptr)
                {
                    // 这里学到了怎么跳出两次循环的做法
                    // 哇哇哇哇哇哇嗷呜~~~~~~~~~~~~~~~~!
                    flag = 1;
                }
            }
            if(flag==1)
            {
                break;
            }
        }
        return minDepth;
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值