您的位置:首页 > 其它

leetcode-1-二叉树的最小深度

2019-02-26 21:01 246 查看
版权声明:有问题可以私信哦 https://blog.csdn.net/yanguang1470/article/details/87949055

leetcode-1-二叉树的最小深度

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.

给定一个二叉树,找出其最小深度。
最小深度是从根节点到最近叶子节点的最短路径上的节点数量。
说明: 叶子节点是指没有子节点的节点。
示例:
给定二叉树 [3,9,20,null,null,15,7],

class solution{
public:
int run(TreeNode* root){
}
}

solution1:层次遍历/BFS广度优先

层次遍历,遇到的第一个节点也是最浅的
对于二叉树来说,层次遍历和BFS是等价的。

层次遍历/BFS
.

class Solution {
public:
typedef TreeNode* tree;//因为要用到队列,STL队列是一个容器,要定义容器的类型,这里定义容器要用到的类型定义
int run(TreeNode *root)
{
if(root == nullptr)
return 0;
//空树
queue<tree> qu;
tree last , now;//队列中的最后一个元素和第一个元素
int level , size;//当前层数和队列大小
last = now = root;//初始化队列游标
level = 1;//既然树不为空,level至少为1
qu.push(root);//根入队
while(qu.size())//只要队列不为空
{
now = qu.front();//取出第一个节点
qu.pop();//把它弹出队列
size = qu.size();//更新队列大小
//该节点孩子加到队列中
if(now->left)
qu.push(now->left);
if(now->right)
qu.push(now->right);
//如果队列大小没变,没孩子,是子节点
if(size <
4000
span class="token operator">- qu.size() == 0)
break;//this node has no child. it's the first node I meet.
if(now == last)
{
//这一层的头与尾汇合了
level++;
if(qu.size() != 0)//这个似乎没用
//到下一层
last = qu.back();
}
}
return level;

}

};

solution2:递归

就是短

递归

class Solution {
public:
int run(TreeNode *root)
{
//若是空树返回0
if (root == nullptr)
return 0;
//如果左子树为空,返回右子树+1
if(root->left == nullptr)
return run(root->right)+1;
//如果右子树为空,返回左子树+1
if(root->right == nullptr)
return run(root->left)+1;
//如果儿女双全,返回较小的一个;
int leftDepth = run(root->left);
int rightDepth = run(root->right);
return (leftDepth < rightDepth) ? leftDepth+1 : rightDepth+1;
}
};

做个简单题这么费劲 哭了

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