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 };
  • 相关阅读:
    终于想起了博客园密码
    关于GCD的8题
    idea快捷键 ctrl + shift + f 失效解决方法
    前端和后端日期类型交互
    poi、easypoi和easyexcel的使用
    事务总结
    数据库cte的理解和使用
    mybatis 调用存储过程没有返回值
    postgresql 查询锁表并解锁
    tigase网络核心SockThread详解(十九)
  • 原文地址:https://www.cnblogs.com/MT-ComputerVision/p/6985854.html
Copyright © 2011-2022 走看看