首页 > 其他 > 详细

(二叉树 BFS) leetcode 111. Minimum Depth of Binary Tree

时间:2019-04-16 10:28:56      阅读:111      评论:0      收藏:0      [点我收藏+]

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.

Note: A leaf is a node with no children.

Example:

Given binary tree [3,9,20,null,null,15,7],

    3
   /   9  20
    /     15   7

return its minimum depth = 2.

------------------------------------------------------------------------------------------------------------------------------

求二叉树的最小深度,嗯,这个题可以用DFS,也可以用BFS,我这个题先用BFS写。

 

C++代码:

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    int minDepth(TreeNode* root) {
        queue<TreeNode*> q;
        if(!root)
            return 0;
        q.push(root);
        int sum = 0;
        while(!q.empty()){
            sum++;
            for(int i = q.size(); i > 0; i--){  //必须写循环,如果不写,对于[1,2,3,4,5],将会返回3,与题目要求不符。
                auto t = q.front();
                q.pop();
                if(!t->left &&!t->right) return sum;
                if(t->left) q.push(t->left);
                if(t->right) q.push(t->right);
            }
        }
        return 0;
    }
};

 

(二叉树 BFS) leetcode 111. Minimum Depth of Binary Tree

原文:https://www.cnblogs.com/Weixu-Liu/p/10714886.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!