zoukankan      html  css  js  c++  java
  • 155 二叉树的最小深度

    原题网址:https://www.lintcode.com/problem/minimum-depth-of-binary-tree/description

    描述

    给定一个二叉树,找出其最小深度。

    二叉树的最小深度为根节点到最近叶子节点的距离。
    您在真实的面试中是否遇到过这个题?  

    样例

    给出一棵如下的二叉树:

            1

         /      

       2       3

              /    

            4      5  

    这个二叉树的最小深度为 2

    标签
    二叉树
    Depth-first Search(DFS)
     
    思路:可参照二叉树的最大深度一题。 PS:深度优先搜索上递归。二叉树与递归的题真的很容易懵比,要多练练。
     
    最小深度与最大深度的区别是,返回左右子树深度时,二叉树的深度必须是根结点到叶子结点的距离,所以不能单纯的比较左右子树的递归结果返回较小值,因为对于只有单个孩子的节点,为空的孩子会返回0,但这个节点并非叶子节点,故返回的结果是错误的。
    因此,当发现当前处理的节点有单个孩子是空时,返回一个极大值INT_MAX,防止其干扰结果。转自此文
     

    AC代码:

    /**
     * Definition of TreeNode:
     * class TreeNode {
     * public:
     *     int val;
     *     TreeNode *left, *right;
     *     TreeNode(int val) {
     *         this->val = val;
     *         this->left = this->right = NULL;
     *     }
     * }
     */
    
    class Solution {
    public:
        /**
         * @param root: The root of binary tree
         * @return: An integer
         */
        int minDepth(TreeNode * root) {
            // write your code here
            if (root==NULL)
         {
             return 0;
         }
         if (root->left==NULL&&root->right==NULL)
         {
             return 1;
         }
         int leftDepth=minDepth(root->left);
         int rightDepth=minDepth(root->right);
    
         leftDepth = (leftDepth==0?INT_MAX:leftDepth);
         rightDepth = (rightDepth==0?INT_MAX:rightDepth);
    
         return leftDepth<rightDepth?leftDepth+1:rightDepth+1;
        }
    };

     

    最开始还想用广度优先搜索一层层找下去,但深度值没办法计算,吐血

     

     其他参考:

    https://blog.csdn.net/wutingyehe/article/details/46647081   推荐!原理易懂,代码更简洁。

    https://blog.csdn.net/xspyzm/article/details/70159863

    https://blog.csdn.net/skp127/article/details/51654916

    https://blog.csdn.net/u013115610/article/details/71252441

  • 相关阅读:
    K
    A
    C
    E
    2020/9/14
    hdu5306 hdu3954 cf438D
    2020/9/10-9/11
    题解
    2020/8/31
    2020/8/30
  • 原文地址:https://www.cnblogs.com/Tang-tangt/p/9157837.html
Copyright © 2011-2022 走看看