-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMinimum_Depth_of_Binary_Tree.cpp
More file actions
54 lines (52 loc) · 1.62 KB
/
Minimum_Depth_of_Binary_Tree.cpp
File metadata and controls
54 lines (52 loc) · 1.62 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 binary tree
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
/*
O(N)
*/
class Solution {
public:
int minDepth(TreeNode *root) {
if(!root)return 0;
if(root->left==NULL&&root->right==NULL)return 1;
int result=1, tl=INT_MAX, tr=INT_MAX;
if(root->left)tl=minDepth(root->left);
if(root->right)tr=minDepth(root->right);
return 1+min(tl, tr);
}
int minDepth(TreeNode *root) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
if(root==NULL)return 0;
int res=1;
vector<vector<TreeNode* >> table(2);
int pre=0,cur=1;
table[cur].push_back(root);
while(true)
{
cur=!cur;
pre=!pre;
table[cur].clear();
bool sign=false;
for(int i=0;i<table[pre].size();i++)
{
if(table[pre][i]->left==NULL&&table[pre][i]->right==NULL)
{
sign=true;
break;
}
if(table[pre][i]->left)table[cur].push_back(table[pre][i]->left);
if(table[pre][i]->right)table[cur].push_back(table[pre][i]->right);
}
if(sign)break;
res++;
}
return res;
}
};