题目描述
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.
解题思路1(深度优先遍历):
深度优先遍历,定义一个队列q用来存储已访问过节点的左子树和右子树,定义两个树节点first、last用来标记队列中该层最前面的树节点和最后面的树节点。若first=last,则depth+1。若该节点的左子树和右子树均为空,则找到minimum depth跳出循环,返回depth.否则,继续循环。
代码:
class Solution {
public:
int run(TreeNode *root) {
if(!root)
return 0;
queue<TreeNode*> q;
TreeNode *first,*last;
int depth,size;
last=first=root;
depth=1;
q.push(root);
while(q.size())
{
first=q.front();
q.pop();
size=q.size();
if(first->left)
q.push(first->left);
if(first->right)
q.push(first->right);
if(q.size()==size)
break;
if(last==first)
{
depth++;
if(q.size())
last=q.back();
}
}
return depth;
}
};
解题思路2(递归)
若为空树返回0;
若左子树为空,则返回右子树的最小深度+1;(加1是因为要加上根这一层,下同)
若右子树为空,则返回左子树的最小深度+1;
若左右子树均不为空,则取左、右子树最小深度的较小值,+1;
代码:
class Solution {
public:
int run(TreeNode *root)
{
if(root == NULL) return 0;
if(root->left == NULL) // 若左子树为空,则返回右子树的最小深度+1
{
return run(root->right)+1;
}
if(root->right == NULL) // 若右子树为空,则返回左子树的最小深度+1
{
return run(root->left)+1;
}
// 左右子树都不为空时,取较小值
int leftDepth = run(root->left);
int rightDepth = run(root->right);
return (leftDepth<rightDepth)?(leftDepth+1):(rightDepth+1);
}
};