Minimum Depth of Binary Tree

二叉树的最小深度

 

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

 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

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

posted @ 2016-06-21 13:50  牧马人夏峥  阅读(73)  评论(0编辑  收藏  举报