zl程序教程

您现在的位置是:首页 >  其它

当前栏目

Minimum Depth of Binary Tree

of Tree Binary minimum depth
2023-09-14 08:57:33 时间

二叉树的最小深度

 

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

 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

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