Skip to content

Commit a3d9b42

Browse files
authored
Merge pull request #2776 from Abe0770/main
Create 0111-minimum-depth-of-binary-tree.cpp
2 parents 78f2db7 + 2e9c8c9 commit a3d9b42

File tree

1 file changed

+51
-0
lines changed

1 file changed

+51
-0
lines changed

Diff for: cpp/0111-minimum-depth-of-binary-tree.cpp

+51
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
1+
/*
2+
Given a binary tree, find its minimum depth.
3+
4+
The minimum depth is the number of nodes along the shortest path from the root node down to the nearest leaf node.
5+
6+
Note: A leaf is a node with no children.
7+
8+
Ex. Input: root = [3,9,20,null,null,15,7]
9+
Output: 2
10+
11+
Time : O(N)
12+
Space : O(N)
13+
*/
14+
15+
/**
16+
* Definition for a binary tree node.
17+
* struct TreeNode {
18+
* int val;
19+
* TreeNode *left;
20+
* TreeNode *right;
21+
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
22+
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
23+
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
24+
* };
25+
*/
26+
class Solution {
27+
public:
28+
int minDepth(TreeNode* root) {
29+
if(!root)
30+
return 0;
31+
int count = 1;
32+
queue <TreeNode*> q;
33+
q.push(root);
34+
while(!q.empty()) {
35+
int size = q.size();
36+
for(int i = 0 ; i < size ; i++) {
37+
TreeNode* front = q.front();
38+
if(!front -> left && !front -> right)
39+
return count;
40+
if(front -> left)
41+
q.push(front -> left);
42+
if(front -> right)
43+
q.push(front -> right);
44+
45+
q.pop();
46+
}
47+
count++;
48+
}
49+
return count;
50+
}
51+
};

0 commit comments

Comments
 (0)