链接
https://leetcode-cn.com/problems/minimum-depth-of-binary-tree/
耗时
解题:12 min
题解:3 min
题意
给定一个二叉树,找出其最小深度。
最小深度是从根节点到最近叶子节点的最短路径上的节点数量。
说明: 叶子节点是指没有子节点的节点。
思路
BFS 层序遍历,在遇到第一个叶节点时,返回当前层数。
时间复杂度:
O
(
n
)
O(n)
O(n) n 为二叉树节点数量
AC代码
class Solution {
public:
int minDepth(TreeNode* root) {
if(root == NULL) return 0;
queue<TreeNode*> q;
q.push(root);
int ans = 0;
while(!q.empty()) {
ans++;
int n = q.size();
for(int i = 0; i < n; ++i) {
TreeNode* now = q.front();
q.pop();
if(now->left == NULL && now->right == NULL) {
return ans;
}
if(now->left != NULL) q.push(now->left);
if(now->right != NULL) q.push(now->right);
}
}
return ans;
}
};
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)