给定一个二叉树,找出其最小深度。
最小深度是从根节点到最近叶子节点的最短路径上的节点数量。
说明: 叶子节点是指没有子节点的节点。
/**
* 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) {
// if(!root)
// return 0;
// else if(!root->left&&!root->right)
// return 1;
// else if(root->left&&!root->right)
// return minDepth(root->left)+1;
// else if(!root->left&&root->right)
// return minDepth(root->right)+1;
// else
// return min(minDepth(root->left),minDepth(root->right))+1;
// if(root==NULL)return 0;
// int left_depth=minDepth(root->left);
// int right_depth=minDepth(root->right);
// if(left_depth&&right_depth)
// return min(left_depth,right_depth)+1;
// else
// return max(left_depth,right_depth)+1;
if(root==NULL)return 0;
queue<TreeNode *>q;
q.push(root);
int depth=0;
while(!q.empty()){
queue<TreeNode *>qt;
depth++;
while(!q.empty()){
TreeNode * temp=q.front();
q.pop();
if(!temp->left&&!temp->right)return depth;
if(temp->left)qt.push(temp->left);
if(temp->right)qt.push(temp->right);
}
q=qt;
}
return depth;
}
};