美文网首页
[Leetcode]111. Minimum Depth of

[Leetcode]111. Minimum Depth of

作者: beautymo | 来源:发表于2018-06-12 21:17 被阅读0次

    题目描述:
    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.

    Note: A leaf is a node with no children.


    例子.png

    解释:就是返回所有叶子节点到根节点中最短的那条道的长度

    递归写法方法一:

    该方法参考博客:https://www.tianmaying.com/tutorial/LC111

    这道题目算是一道非常简单的题目,我们不妨设minDepth(t)表示“以t为根节点的子树中,所有叶子节点中深度最小的一个节点的深度”,那么我们想要求的答案就是minDepth(root)。

    那么如何求解minDepth(t)呢?

    我们不妨分情况进行讨论:

    如果t是叶子节点,即不存在左儿子和右儿子,那么显然有minDepth(t) = 1。
    如果t有左儿子,但是没有右儿子,那么显然有minDepth(t) = minDepth(t -> left) + 1。
    如果t有右儿子,但是没有左儿子,那么显然有minDepth(t) = minDepth(t -> right) + 1。
    如果t有两个儿子,那么就需要从这两种方案里面选一个使得minDepth(t)最小的,即minDepth(t) = min(minDepth(t -> left) + 1, minDepth(t -> right + 1)) = min(minDepth(root -> left), minDepth(root -> right)) + 1。
    这样一来,就将minDepth(t)这个问题转化成了两个规模较小的问题minDepth(t -> left)和minDepth(t -> right),从而可以使用递归的方法进行求解,具体的实现请参考之后的代码。

    /**
     * Definition for a binary tree node.
     * struct TreeNode {
     *     int val;
     *     TreeNode *left;
     *     TreeNode *right;
     *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
     * };
     */
    class Solution{
    public:
        int minDepth(TreeNode *root){
            if(root == NULL) return 0;
            if(root->left == NULL && root->right == NULL) return 1;
            if(root->left == NULL && root->right != NULL) return minDepth(root->right)+1;
            if(root->right == NULL && root->left != NULL) return minDepth(root->left)+1;
            return min(minDepth(root->right)+1,minDepth(root->left)+1);
              
        }
    };
    

    递归写法二

    这也是我从网上看来的,无奈忘了出处是哪,在此表示抱歉

    思路:
    不管什么时候,左右子树两边都进行递归计算树的深度,返回左右两边深度较小的那个,若某一边子树不存在,则认为该深度为很大(即此时返回的是子树存在的那边的最小深度)

    代码如下

    /**
     * Definition for a binary tree node.
     * struct TreeNode {
     *     int val;
     *     TreeNode *left;
     *     TreeNode *right;
     *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
     * };
     */
    
    class Solution{
    public:
        int minDepth(TreeNode *root){
      
             if (root==NULL)return 0;  
             int LDepth=minDepth(root->left);  
             int RDepth=minDepth(root->right);  
              
             if(LDepth==0&&RDepth==0)  
             return 1;  
             if(LDepth==0)  
             LDepth=INT_MAX;  
             if(RDepth==0)  
            RDepth=INT_MAX;  
              
           return min(LDepth,RDepth)+1;  
           
        }
    };
    

    其他思路

     可以把每一条路径都记录下来,比较出最小的那个,等我学会了c++的list再来写!

    相关文章

      网友评论

          本文标题:[Leetcode]111. Minimum Depth of

          本文链接:https://www.haomeiwen.com/subject/xeomhftx.html