-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path111_Minimum_Depth_of_Binary_Tree.cpp
More file actions
54 lines (47 loc) · 1.36 KB
/
111_Minimum_Depth_of_Binary_Tree.cpp
File metadata and controls
54 lines (47 loc) · 1.36 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
//Recursive Solution
class Solution {
public:
int minDepth(TreeNode* root) {
if(root == NULL) return 0;
else if(root->right==NULL && root->left==NULL) return 1;
else if(root->right==NULL) return minDepth(root->left)+1;
else if(root->left==NULL) return minDepth(root->right)+1;
return min(minDepth(root->right), minDepth(root->left))+1;
}
};
//BFS
class Solution {
public:
int minDepth(TreeNode* root) {
if (root==NULL) return 0;
queue<TreeNode> q;
q.push(root);
int left_level_cnt = 1, right_level_cnt = 1;
TreeNode* temp;
while (!q.empty()){
qi = q.front();
q.pop();
if (qi->left==NULL && qi->right==NULL) return max(left_level_cnt, right_level_cnt);
if (qi->left != NULL){
temp = qi->left;
q.push(temp);
left_level_cnt +=1;
}
if (qi->right != NULL){
temp = qi->right;
q.push(temp);
right_level_cnt +=1;
}
}
return 0;
}
};