(树_02)求树的最小深度

111. 二叉树的最小深度

 

解题思路

dfs:if条件判断

1.根节点为空

2.左右孩子为空

3.左孩子不为空:递归调用minDepth,把左孩子节点传入,跟depth比较,取两者更小的那个

4.右孩子不为空:递归调用minDepth,把右孩子节点传入,跟depth比较,取两者更小的那个

class Solution {
public:
    int minDepth(TreeNode* root) {
        if(root == nullptr) return 0;
        if(root->left == nullptr && root->right ==nullptr) return 1;
        
        int min_depth = 63355;
        if(root->left != nullptr)  
        {
            min_depth =  min(minDepth(root->left), min_depth);
        }
        if(root->right != nullptr)
        {
            min_depth =  min(minDepth(root->right), min_depth);
        }
        return min_depth+1;
    }
};

 

bfs:用队列一层一层比较,queue<pair<TreeNode*, int>> que,用que.empalce()方法插入。

1.根节点为空

2.插入root节点以及深度1到que

3.当que不为空时进行循环3~6步,取出que中存放的节点与深度

4.若节点没有左右孩子,则直接返回深度

5.若节点左孩子不为空,则将左孩子节点以及深度+1插入到que

6.若节点右孩子不为空,则将左孩子节点以及深度+1插入到que

class Solution {
public:
    int minDepth(TreeNode* root) {
        if(root == nullptr) return 0;

        queue<pair<TreeNode*, int>> que;
        que.emplace(root, 1);
        while(!que.empty())
        {
            TreeNode* node = que.front().first;
            int depth = que.front().second;
            que.pop();

            if(node->left == nullptr && node->right == nullptr) return depth;
            if(node->left != nullptr)
            {
                que.emplace(node->left, depth+1);
            }
            if(node->right != nullptr)
            {
                que.emplace(node->right, depth+1);
            }
        }
        return 0;
       
    }
};

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Jasscical

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值