[LeetCode] Minimum Depth of Binary Tree(bfs)

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.

/**
 * 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) {
        queue<TreeNode*> q;
        if(root==NULL)
            return 0;
        q.push(root);
        q.push(NULL);//q中出现NULL表示本层结束
        return bfs(0,q);
    }
private:
    int bfs(int depth,queue<TreeNode*> &q){
        queue<TreeNode*> temp;
        while(!q.empty()){

            TreeNode *p =  q.front();
            q.pop();
            if(p==NULL)//本层结束
            {
                depth++;
                q = temp;
                while(!temp.empty())
                  temp.pop();
                q.push(NULL);
                continue;
            }
            if(p->left !=NULL)
                temp.push(p->left);
            if(p->right != NULL)
                temp.push(p->right);
            if(p->left==NULL && p->right==NULL)
                return depth+1;
        }//end while
    }
};
原文地址:https://www.cnblogs.com/Xylophone/p/3890419.html