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.
struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
1 递归求解
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;
}
}
};
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
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 不能随机存取
#include <queue>
using namespace std;
定义
queue<elem> queT; //queue 采用模板类实现,queue 对象的默认构造形式:
插入删除
push(elem);//往队尾添加元素
pop(); //从队头移除第一个元素
back(); //返回最后一个元素
front(); //返回第一个元素
赋值操作
queue& operator=(const queue &que);//重载等号操作
empty(); //判断队列是否为空,如果为空则返回true
size(); //返回队列的大小