zoukankan      html  css  js  c++  java
  • 111. Minimum Depth of Binary Tree

    111. Minimum Depth of Binary Tree

    问题描述:

    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 /**
     2  * Definition for a binary tree node.
     3  * struct TreeNode {
     4  *     int val;
     5  *     TreeNode *left;
     6  *     TreeNode *right;
     7  *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
     8  * };
     9  */
    10  #include <queue>
    11 class Solution {
    12 public:
    13     int minDepth(TreeNode* root) {
    14        if(!root) return 0;
    15        if(!root->left && !root->right) return 1;
    16        int left = minDepth(root->left);
    17        int right = minDepth(root->right);
    18        if(left == 0)
    19        return right + 1;
    20        if(right == 0)
    21        return left + 1;
    22        return left<right?left+1:right+1;
    23     }
    24 };
  • 相关阅读:
    fastjson对String、JSONObject、JSONArray相互转换
    查看各进程分别占用多少服务器内存
    如何关闭或删除阿里云云盾安骑士
    docker 镜像操作
    docker 容器命令
    docker换源
    centos8 docker安装
    基本概念
    自动生成文件注释和函数注释
    Pycharm新建文件时自动添加基础信息
  • 原文地址:https://www.cnblogs.com/MT-ComputerVision/p/6985854.html
Copyright © 2011-2022 走看看