欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 房产 > 建筑 > leetcode111 二叉树的最小深度

leetcode111 二叉树的最小深度

2025/5/16 22:58:16 来源:https://blog.csdn.net/dokii1/article/details/147013767  浏览:    关键词:leetcode111 二叉树的最小深度

相对于 104.二叉树的最大深度 ,本题还也可以使用层序遍历的方式来解决,思路是一样的。

最小深度的定义:从根节点到最近叶子节点的最短路径上的节点数量。

特别注意:

  1. 如果一个子树不存在,就不能用它来计算深度(因为它不是叶子节点路径)

  2. 只有当一个节点没有左右子树时,它才是叶子节点

需要注意的是,只有当左右孩子都为空的时候,才说明遍历的最低点了。如果其中一个孩子为空则不是最低点

迭代法

class Solution {
public:int minDepth(TreeNode* root) {queue<TreeNode*> q;if(root == nullptr) return 0;q.push(root);int dep = 1;while(!q.empty()){int size = q.size();for(int i = 0; i < size; i++){TreeNode* cur = q.front();q.pop();if(!cur->left  && !cur->right) return dep;if(cur->left) q.push(cur->left);if(cur->right) q.push(cur->right);}dep++;}return dep;}
};

DFS前序遍历 + 传递当前深度

class Solution {
private:int mindp = INT_MAX;void traverse(TreeNode* cur, int level){if(cur == nullptr) return;if(!cur->left && !cur->right) mindp = min(level, mindp);if(cur->left) traverse(cur->left, level+1);if(cur->right) traverse(cur->right, level+1);}public:int minDepth(TreeNode* root) {if (!root) return 0; traverse(root, 1);return mindp;}
};

 递归解法(DFS)

int minDepth(TreeNode* root) {if (!root) return 0;          // 情况1:空节点if (!root->left)              // 情况2:只有右子树return minDepth(root->right) + 1;if (!root->right)             // 情况3:只有左子树return minDepth(root->left) + 1;return min(minDepth(root->left), minDepth(root->right)) + 1; // 情况4:左右子树都有
}

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

热搜词