'LeetCode'水题一道: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.

思路

  • 一般做法是深度优先遍历,分别递归左右子树,求出两边的最小距离,取较小值+1.我想既然是求最短路径,显然广度优先搜索更为高效,搜索到的第一个叶子节点一定是离根节点最近的。
  • 广度优先搜索会遇到一个问题,就是如何标记当前节点的深度。我采用的办法是再创建一个队列levelqueue,存放每一层的进入队列的节点,这样当一层遍历结束后,就可以通过queue为空来判断每一层遍历的终点,每层遍历后深度depth加1。
  • 设置标记为noleft,当noleft为真且没有右孩子时,此节点即为离根节点最近的叶子节点,返回当前深度即可。

代码

/**
 * Definition for binary tree
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    int minDepth(TreeNode *root) {
        if (!root) return 0;
        queue<TreeNode*> que;
        queue<TreeNode*> levelq;
        que.push(root);
        int depth=1;
        while(!que.empty()){
            bool first = true;
            bool noleft=false;
            while(!que.empty()){
                TreeNode* tmp = que.front();
                que.pop();
                noleft = false;
                if (tmp->left)  levelq.push(tmp->left);
                else{
                    noleft = true;
                }   
                if (tmp->right) levelq.push(tmp->right);
                else{
                    if (noleft){
                        return depth;
                    }
                }   
                first = false;
            }
            depth += 1;
            while(!levelq.empty()){
                que.push(levelq.front());
                levelq.pop();
            }
        }
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值