二叉树的最小深度

  • minimum depth of binary tree

Given a binary tree, find its minimum depth.
The minimum depth is the number of nodes along the shortest path from the root node down to the nearest leaf node.

  • 题目大意:给定一颗二叉树,找到它的最小深度。最小深度指的是,从根节点到最近的叶子节点,沿着这条路径走过的节点的数目。

  • 思路:利用队列采用层序遍历,一旦找到一个叶节点,它肯定是最短的。

  • 代码:

class Solution
{
    public:
        typedef TreeNode* tree;
        int run(TreeNode *root)
        {
            // 层序遍历,一旦找到一个叶节点,它肯定是最短的
            if (root == NULL)return 0;
            queue<tree> qu;
            tree now = root; // 记录该层的当前节点
            tree last = root; // 记录该层的最后一个节点
            int level = 1;
            int size = 0;
            qu.push(root);
            while (!qu.empty())
            {
                now = qu.front(); // 取队首
                qu.pop(); // 出队首
                size = qu.size();
                if (now->left != NULL)qu.push(now->left);
                if (now->right != NULL)qu.push(now->right);
                // 没有元素进队,说明这是一个叶子节点,找到的第一个叶子节点为最短的
                if (size - qu.size() == 0)break;
                // last==now,说明当前节点走到了该层的最后一个节点
                if (last == now)
                {
                    level++;
                    // last指向下一层的最后一个节点
                    if (!qu.empty())last = qu.back();
                }
            }
            return level;
        }
};
  • 测试结果:

 

转载于:https://www.cnblogs.com/Yang-Yuanlin/p/10018320.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值