题目描述

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

输入

复制

{1,2,3,4,5}

输出

复制

2

/**
 * struct TreeNode {
 *    int val;
 *    struct TreeNode *left;
 *    struct TreeNode *right;
 * };
 */

class Solution {
public:
    /**
     *
     * @param root TreeNode类
     * @return int整型
     */
    int run(TreeNode* root) {
        // write code here
        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);
    }
    
};

/**
 * struct TreeNode {
 *    int val;
 *    struct TreeNode *left;
 *    struct TreeNode *right;
 * };
 */

class Solution {
public:
    typedef TreeNode *tree;
    /**
     *
     * @param root TreeNode类
     * @return int整型
     */
    int run(TreeNode* root) {
        // write code here
        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;
        
    }
};

最新文章

  1. miniui设置边框的方法
  2. poj: 2739
  3. UVA 272 TEX Quotes
  4. Ejection chain 与交错路
  5. flask开发restful api系列(3)--利用alembic进行数据库更改
  6. ONFI闪存数据通道接口标准
  7. Factory Pattern(工厂模式)
  8. R语言笔记3--实例1
  9. 翻译:Identifier Name标识符命名规则
  10. 【转】Javascript错误处理——try…catch
  11. 树上倍增求LCA及例题
  12. 微信接收QQ邮箱e-mail
  13. vue实现筛选功能,文字选中变色
  14. 迅速上手:使用taro构建微信小程序基础教程
  15. Dispatch Queue 之内存中常驻的几个结构
  16. January 30th, 2018 Week 05th Tuesday
  17. Js数组里剔除指定的元素(不是指定的位置)
  18. alibaba fastjson TypeReference 通过字符串反射返回对象
  19. ubuntu16.04安装网易云音乐
  20. iOS:UIButton按钮的详解

热门文章

  1. spring-boot-route(十)多数据源切换
  2. TP5隐藏入口文件
  3. Axure实现vcg官网首页原型图
  4. DX12龙书 02 - DirectXMath 库中与向量有关的类和函数
  5. 自定义Antd Pro 默认元素
  6. Spring Boot 系列:最新版优雅停机详解
  7. Linux Centos7 安装Docker-CE
  8. package wang/test is not in GOROOT (/usr/local/go/src/wang/test)
  9. 【荐】JavaScript图片放大技术(放大镜)示例代码
  10. http请求需要了解的一些信息