前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >[编程题]minimum-depth-of-binary-tree

[编程题]minimum-depth-of-binary-tree

作者头像
宋天伦
发布2020-07-16 11:26:26
3030
发布2020-07-16 11:26:26

题目来源

时间限制:C/C++ 1秒,其他语言2秒空间限制:C/C++ 32M,其他语言64M

题目描述

求给定二叉树的最小深度。最小深度是指树的根结点到最近叶子结点的最短路径上结点的数量。

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.

解题思路

  • 递归,若为空树返回0;
  • 若左子树为空,则返回右子树的最小深度+1;(加1是因为要加上根这一层,下同)
  • 若右子树为空,则返回左子树的最小深度+1;
  • 若左右子树均不为空,则取左、右子树最小深度的较小值,+1;

来自 @Msean

  • C++11,其中有一个是新的关键字nullptr, 如果我们的编译器是支持nullptr的话,那么我们应该直接使用nullptr来替代NULL的宏定义。正常使用过程中他们是完全等价的。

参考代码

代码语言:javascript
复制
// 运行时间:12ms
// 占用内存:1024k

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

参考文献

Author: Frytea

Title: 编程题minimum-depth-of-binary-tree

Link: https://cloud.tencent.com/developer/article/1662780

Copyright: This work by TL-Song is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License.

本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 题目来源
  • 题目描述
  • 解题思路
  • 参考代码
  • 参考文献
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档