您的位置:首页 > 其它

【LeetCode】111. Minimum Depth of Binary Tree

2016-10-06 14:55 330 查看
题目:

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.

分析:

这道题的要求是求一颗二叉树的最小高度,即从根节点到叶子结点所经过的结点数目。我的想法是使用BFS来求解这个问题。

设3个变量depth,cur,next来分别记录二叉树的高度,当前层没遍历过的结点数,下一层没遍历的结点数。每遍历一层,depth就加1.当遍历到叶子结点时,返回depth。这个算法的复杂度为O(N).

代码:

/**
* 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;
int depth = 0,cur = 0,next = 0;
queue<TreeNode*> q;
q.push(root);
depth++;
cur++;
while(!q.empty())
{
TreeNode* temp =q.front();
q.pop();
cur--;
if(temp->left == NULL&&temp->right ==NULL)
return depth;
if(temp->left!=NULL)
{
q.push(temp->left);
next++;
}

if(temp->right != NULL)
{
q.push(temp->right);
next++;
}
if(cur == 0)
{
depth++;
cur = next;
next = 0;
}

}
return depth;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  leetcode