avatar

目录
Leetcode 111 二叉树的最小深度

LeetCode 111:二叉树的最小深度

求给定二叉树的最小深度。最小深度是指树的根结点到最近叶子结点的最短路径上结点的数量。

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.

Code
1
2
3
4
5
6
struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};

1 递归求解

Code
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
class Solution {
public:
int run(TreeNode *root) {
int minimum = 0;
if(root==NULL)
{
return minimum;
}
int ld = run(root->left); //递归求解
int rd = run(root->right);

if(ld * rd > 0) //考虑非完全二叉树的情况
{
return (ld>rd?rd:ld)+1;
}
else //左右子树有一个深度为0,所以取大的深度继续递归
{
return (ld>rd?ld:rd)+1;
}

}
};
Code
1
2
3
4
5
6
7
8
9
10
11
class Solution 
{
public:
int run(TreeNode* root)
{
if (root == nullptr) return 0;
if (root->left == nullptr) return run(root->right) + 1;
if (root->right == nullptr) return run(root->left) + 1;
return min(run(root->left) , run(root->right)) + 1;
}
};

2 非递归,BFS

Code
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
class Solution {
public:
int run(TreeNode *root) {
if(root == NULL)
return 0;
queue<TreeNode*> que;
que.push(root);
int depth = 0;
while(!que.empty())
{

int size = que.size(); //当前待遍历层的结点数
depth++;
//遍历当前层
for(int i = 0; i < size; ++i)
{
TreeNode* tmp = que.front();
if(tmp->left != NULL)
que.push(tmp->left);
if(tmp->right != NULL)
que.push(tmp->right);
que.pop();
// 找到第一个叶子节点,返回
if(tmp->left == NULL && tmp->right == NULL)
return depth;
}
}
return -1;
}
};

C++ queue 复习总结

FIFO 不能随机存取

Code
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
 #include <queue>
using namespace std;

定义
queue<elem> queT; //queue 采用模板类实现,queue 对象的默认构造形式:

插入删除
push(elem);//往队尾添加元素
pop(); //从队头移除第一个元素
back(); //返回最后一个元素
front(); //返回第一个元素

赋值操作
queue& operator=(const queue &que);//重载等号操作

empty(); //判断队列是否为空,如果为空则返回true
size(); //返回队列的大小
文章作者: Bellium
文章链接: https://belliumtang.github.io/2020/03/04/Leetcode111/
版权声明: 本博客所有文章除特别声明外,均采用 CC BY-NC-SA 4.0 许可协议。转载请注明来自 Bellium
打赏
  • 微信Wechatpay
    微信Wechatpay
  • 支付宝Alipay
    支付宝Alipay