/
Minimum_Depth_of_Binary_Tree.cpp
72 lines (49 loc) · 1.14 KB
/
Minimum_Depth_of_Binary_Tree.cpp
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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
#include <iostream>
struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
class Solution {
public:
Solution(){
theMinDepth = 65560;
depth = 0;
isRoot = 1;
}
int minDepth(TreeNode *root) {
if(isRoot == 1 && root == NULL){
theMinDepth = 0;
}
isRoot = 0;
if(root == NULL){
}
else{
depth++;
if(root->left == NULL && root->right ==NULL){
if(theMinDepth > depth){
theMinDepth = depth;
}
}
minDepth(root->left);
minDepth(root->right);
depth--;
}
return theMinDepth;
}
private:
int theMinDepth;
int depth;
int isRoot;
};
int main(){
Solution a;
TreeNode t1(1),t2(2),t3(3),t4(4),t5(5);
TreeNode* pt1=&t1, *pt2=&t2, *pt3=&t3, *pt4=&t4, *pt5=&t5;
pt1->right=pt2;
//pt1->right=pt3;
// pt2->left=pt4;
// pt3->right=pt5;
std::cout<<a.minDepth(NULL)<<std::endl;
}