-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMaximum_Depth_of_Binary_Tree.cpp
More file actions
53 lines (49 loc) · 1.42 KB
/
Copy pathMaximum_Depth_of_Binary_Tree.cpp
File metadata and controls
53 lines (49 loc) · 1.42 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
/**
* 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 maxDepth(TreeNode *root) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
vector<vector<int> > res;
if(root==NULL)return 0;
queue<TreeNode* > queue;
vector<int> row;
queue.push(root);
int pre=1,cur=0,depth=0;
while(!queue.empty())
{
TreeNode *item=queue.front();
queue.pop();
row.push_back(item->val);
pre--;
if(item->left)queue.push(item->left),cur++;
if(item->right)queue.push(item->right),cur++;
if(pre==0)
{
depth++;
pre=cur;
cur=0;
row.clear();
}
}
return depth;
}
int maxDepth(TreeNode *root) {
return maxDepthHelper2(root);
}
int maxDepthHelper(TreeNode *node) {
if (node == NULL) return 0;
return 1+max(maxDepthHelper2(node->left), maxDepthHelper2(node->right));
}
};