반응형
https://leetcode.com/problems/minimum-depth-of-binary-tree/description/
Minimum Depth of Binary Tree - LeetCode
Can you solve this real interview question? Minimum Depth of Binary Tree - Given a binary tree, find its minimum depth. The minimum depth is the number of nodes along the shortest path from the root node down to the nearest leaf node. Note: A leaf is a no
leetcode.com
BFS로 한 depth씩 탐색하며, 리프 노드를 만났을 때의 depth를 반환해줍니다.
class Solution {
public:
int minDepth(TreeNode* root) {
if(!root) return 0;
int depth = 0;
queue<TreeNode*> q;
q.push(root);
while(!q.empty()) {
depth++;
int sz = q.size();
while(sz--) {
TreeNode* node = q.front(); q.pop();
int curSize = q.size();
if(node->left) q.push(node->left);
if(node->right) q.push(node->right);
if(curSize == q.size()) return depth;
}
}
return depth;
}
};
반응형
'Algorithm' 카테고리의 다른 글
LeetCode 802. Find Eventual Safe States (0) | 2023.07.12 |
---|---|
LeetCode 863. All Nodes Distance K in Binary Tree (0) | 2023.07.11 |
LeetCode 2024. Maximize the Confusion of an Exam (0) | 2023.07.08 |
LeetCode 1493. Longest Subarray of 1's After Deleting One Element (0) | 2023.07.05 |
LeetCode 137. Single Number II (0) | 2023.07.05 |