【Leetcode题解】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.

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();  //返回队列的大小
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值