leetcode上的一道题:minimum-depth-of-binary-tree
问题描述: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.
大意:给定一棵二叉树,求此二叉树的最小深度。这个最小深度的意思就是,最小深度是从根节点到最近叶节点的最短路径的节点数。
比较常规的思路分别是DFS和BFS,从算法的效率上来讲效率比较高的应该是BFS.
DFS思路:用递归的方式来求出到达叶子节点所需要的节点数,从中选择最小的,这种方式要遍历所有的叶子节点,从效率上来讲比较低效。
BFS思路:采用层次遍历的方式当到达第一个叶子节点的时候就停止BFS此时的层数就是最小深度。效率较高。
下面是DFS代码:
class Solution {
public:
int run(TreeNode *root) {
if(root==nullptr) return 0;
else if(root->left==nullptr&&root->right==nullptr) return 1;
else{
if(root->left==nullptr)
return run(root->right)+1;
else if(root->right==nullptr)
return run(root->left)+1;
else{
int lf=run(root->left)+1;
int rh=run(root->right)+1;
return min(lf,rh);
}
}
}
};
下面是BFS代码:
class Solution {
public:
int run(TreeNode *root) {
if(root==nullptr) return 0;
else{
queue<TreeNode *> que;
que.push(root);
int deepth=0;//记录深度
int num=1;//记录每一层的节点数
bool flag=true;
while(!que.empty()&&flag){
int _num=0;
for(int i=0;i<num;i++){
TreeNode * temp=que.front();
que.pop();
if(temp->left==nullptr&&temp->right==nullptr){
flag=false;
break;
}
if(temp->left!=nullptr){
que.push(temp->left);
_num++;
}
if(temp->right!=nullptr){
que.push(temp->right);
_num++;
}
}
num=_num;
deepth++;
}
return deepth;
}
}