题目大意:给出一颗二叉树,求出该二叉树的最小深度。最小深度为从根节点到离它最近的叶子节点的路径上的节点数。
算法思想:
1.借助队列,层序遍历该二叉树,为每个节点编上节点深度。
2.只需找出从队列中最先发现的叶子节点即可,返回它的节点深度。
代码如下:
/**
* 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==NULL) return 0;
queue<pair<TreeNode*,int>> Q;
Q.push(make_pair(root,1));
while(!Q.empty()){
pair<TreeNode*,int> tmp=Q.front();
Q.pop();
if(tmp.first->left==NULL&&tmp.first->right==NULL) return tmp.second;
if(tmp.first->left!=NULL)
Q.push(make_pair(tmp.first->left,tmp.second+1));
if(tmp.first->right!=NULL)
Q.push(make_pair(tmp.first->right,tmp.second+1));
}
}
};