码迷,mamicode.com
首页 > 其他好文 > 详细

Minimum Depth of Binary Tree

时间:2016-06-21 14:02:17      阅读:125      评论:0      收藏:0      [点我收藏+]

标签:

二叉树的最小深度

技术分享

 

采用递归的方式求左右结点的高度,注意判断一个结点是否是叶子结点(左右子树都不存大)。

技术分享
 int minDepth(TreeNode *root)
      {
          return minDepth(root, false);
      }
      int minDepth(TreeNode *root, bool hasbrothers)
      {
          if (root == nullptr)return hasbrothers ? INT_MAX : 0;

          return 1 + min(minDepth(root->left, root->right != nullptr),
              minDepth(root->right, root->left != nullptr));

      }
View Code

 同理可判断最大深度,因为是求最大值,所以无需判断该结点是否是叶子结点(如果不是叶子结点,肯定不是最大深度)。

Minimum Depth of Binary Tree

标签:

原文地址:http://www.cnblogs.com/573177885qq/p/5603382.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!