posts - 137,comments - 0,views - 40818
复制代码
//求一颗二叉树的最大深度  求高度:后序遍历  求深度:前序遍历
int maxDepth(TreeNode* root) {
  return root ? 1 + max(maxDepth(root->left), maxDepth(root->right)) : 0;
}
//求一颗二叉树的最小深度(实质上是后序遍历)
int minDepth(TreeNode* root) {
  if (!root) return 0;
  //int leftDepth = minDepth(root->left);
  //int rightDepth = minDepth(root->right);
  //若左子树为空,右子树不为空
  if (!root->left && root->right) {
    return 1 + minDepth(root->right);
  }
  //若左子树不为空,右子树为空
  else if (root->left && !root->right) {
    return 1 + minDepth(root->left);
  }
  else {
    return 1 + min(minDepth(root->left), minDepth(root->right));
  }
}
复制代码
posted on   wshidaboss  阅读(74)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· winform 绘制太阳,地球,月球 运作规律
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· AI 智能体引爆开源社区「GitHub 热点速览」
· 写一个简单的SQL生成工具
· Manus的开源复刻OpenManus初探
历史上的今天:
2023-03-06 C/C++ 数据结构栈的应用-迷宫的求解
2023-03-06 C/C++ 数据结构链栈的基本操作实现
2023-03-06 C/C++ 数据结构堆排序算法的实现
< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

点击右上角即可分享
微信分享提示