Skip to content

Commit 1702f5f

Browse files
authored
Create 111. Minimum Depth of Binary Tree.cpp
1 parent f485f06 commit 1702f5f

File tree

1 file changed

+67
-0
lines changed

1 file changed

+67
-0
lines changed

Diff for: 111. Minimum Depth of Binary Tree.cpp

+67
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,67 @@
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+
Example:
9+
10+
Given binary tree [3,9,20,null,null,15,7],
11+
12+
3
13+
/ \
14+
9 20
15+
/ \
16+
15 7
17+
return its minimum depth = 2.
18+
19+
Solution one is recursive, two is iterative.
20+
*/
21+
22+
/**
23+
* Definition for a binary tree node.
24+
* struct TreeNode {
25+
* int val;
26+
* TreeNode *left;
27+
* TreeNode *right;
28+
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
29+
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
30+
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
31+
* };
32+
*/
33+
class Solution {
34+
public:
35+
int minDepth(TreeNode* root) {
36+
if ( !root ) return 0;
37+
if ( !root->left ) return minDepth( root->right ) + 1;
38+
if ( !root->right ) return minDepth( root->left ) + 1;
39+
return min( minDepth( root->left ), minDepth( root->right ) ) + 1;
40+
}
41+
};
42+
43+
class Solution {
44+
public:
45+
int minDepth(TreeNode* root) {
46+
if ( !root ) return 0;
47+
int depth = 0;
48+
int width = 0;
49+
queue<TreeNode*> q;
50+
TreeNode *temp = root;
51+
q.push( temp );
52+
while ( !q.empty() )
53+
{
54+
depth++;
55+
width = q.size();
56+
for ( int i = 0; i < width; i++ )
57+
{
58+
temp = q.front();
59+
q.pop();
60+
if ( !temp->left && !temp->right ) return depth;
61+
if ( temp->left ) q.push( temp->left );
62+
if ( temp->right ) q.push( temp->right );
63+
}
64+
}
65+
return depth;
66+
}
67+
};

0 commit comments

Comments
 (0)