分享

二叉树的最小深度

 雪柳花明 2016-10-10

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

二叉树的最小深度为根节点到最近叶子节点的距离。


样例

给出一棵如下的二叉树:

        1

     /     \ 

   2       3

          /    \

        4      5  

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

  1. /** 
  2.  * Definition of TreeNode: 
  3.  * class TreeNode { 
  4.  * public: 
  5.  *     int val; 
  6.  *     TreeNode *left, *right; 
  7.  *     TreeNode(int val) { 
  8.  *         this->val = val; 
  9.  *         this->left = this->right = NULL; 
  10.  *     } 
  11.  * } 
  12.  */  
  13. class Solution {  
  14. public:  
  15.     /** 
  16.      * @param root: The root of binary tree. 
  17.      * @return: An integer 
  18.      */  
  19.     int minDepth(TreeNode *root) {  
  20.         // write your code here  
  21.         if (root == NULL)  
  22.         {  
  23.             return 0;  
  24.         }  
  25.         if (root->left == NULL && root->right == NULL)  
  26.         {  
  27.             return 1;  
  28.         }  
  29.         if (root->left == NULL)  
  30.         {  
  31.             return 1 + minDepth(root->right);  
  32.         }  
  33.         else if (root->right == NULL)  
  34.         {  
  35.             return 1 + minDepth(root->left);  
  36.         }  
  37.         else   
  38.         {  
  39.             int left = minDepth(root->left);  
  40.             int right = minDepth(root->right);  
  41.           
  42.             return 1 + min(left, right);  
  43.         }  
  44.     }  
  45. };  

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多