Leetcode:minimum-depth-of-binary-tree

本文介绍了解决LeetCode中最小深度二叉树问题的两种方法:深度优先搜索(DFS)递归算法及广度优先搜索(BFS)。通过递归深度遍历树的节点,遇到四种情况分别处理,并给出代码实现;第二种方法使用队列进行层序遍历,直至找到第一个叶节点,其深度即为最小。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Leetcode:minimum-depth-of-binary-tree

Given a binary tree, find its minimumdepth.The minimum depth is the number of nodes along the shortest path from theroot node down to the nearest leaf node.

解决思路如下:

深度遍历树结点,遇到四种情况

(1)存在左子节点,但不存在右子节点,因为非叶节点,还需要朝左遍历下去,深度加1。

(2)存在右子节点,但不存在左子节点,因为非叶节点,还需要朝右遍历下去,深度加1。

(3)左右子节点均存在,因为是求最小深度,因此求得的应当是左和右子节点当中深度比较小的结点。

(4)是叶结点,返回具体的深度。

代码如下:

int run(TreeNode *root) {
        if(root==NULL)
            return 0;
        return depthnum(root,1);
    }
    
    int depthnum(TreeNode* root, int depth)
    {
        if(root->left && !root->right)
            return depthnum(root->left,++depth);
        else if(!root->left && root->right)
            return depthnum(root->right,++depth);
        else if(root->left && root->right)
        {
            depth++;
            return min(depthnum(root->left,depth),depthnum(root->right,depth));
        }
        else 
            return depth;
}

网上还提供了还有一种方法,是利用队列按层遍历,解题思路是按层遍历直到找到第一个叶结点,此时的深度必为最小。

代码如下:

int run(TreeNode *root) {
    //采用广度优先搜索,或者层序遍历,找到的第一个叶节点的深度即是最浅。
      if(! root) return 0;
      queue<tree> qu;
      tree last,now;
      int level,size;
      last = now = root;
      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(qu.size()-size == 0)break;
        if(last == now){
          level++;
          if(qu.size())last = qu.back();
        }
      }
      return level;
    }
};




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值