leetcode每日一道(1):如何求二叉树的最小(最大)深度

题目:求给定二叉树的最小深度。最小深度是指树的根结点到最近叶子结点的最短路径上结点的数量。
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.

给定这样一个题目,首先可以有两个思路:

递归思路

可以用递归的思路:从根节点开始,每次都返回左右子树的最小深度。那么整棵树也就遍历一遍,结果也就出来了。

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;
        }
        int nleft = run(root->left);
        int nright = run(root->right);
        return (nleft>nright)?(nright+1):(nleft+1);
    }
};

层序遍历搜索思路

一般上面的思路其实已经够用了,但是其实比较容易想到广度优先搜索,即可以按层遍历,每一层的节点可以依次遍历,一旦遇到了左右子树都是空的节点,就可以返回该节点所在的层数,即最短的层数!

链接:https://www.nowcoder.com/questionTerminal/e08819cfdeb34985a8de9c4e6562e724?f=discussion
来源:牛客网

class Solution {
public:
    typedef TreeNode* tree;
    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;
    }
};
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值