(二叉树 BFS) leetcode 111. 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.

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;
    }
};

猜你喜欢

转载自www.cnblogs.com/Weixu-Liu/p/10714886.html