-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathLeetcode_maximum-depth-of-binary-tree.cc
66 lines (62 loc) · 1.31 KB
/
Leetcode_maximum-depth-of-binary-tree.cc
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
//http://oj.leetcode.com/problems/maximum-depth-of-binary-tree/
/**
* Definition for binary tree
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
int max_depth = 0;
void dfs(TreeNode* node, int depth)
{
if(node)
{
++depth;
if(node->left)
{
dfs(node->left, depth);
}
if(node->right)
{
dfs(node->right, depth);
}
}
max_depth = max_depth > depth ? max_depth : depth;
}
class Solution {
public:
int maxDepth(TreeNode *root) {
max_depth = 0;
dfs(root, 0);
return max_depth;
}
};
//SECOND TRIAL, bfs
class Solution {
public:
int maxDepth(TreeNode *root) {
if(!root)
return 0;
queue<TreeNode*>treeq;
treeq.push(root);
TreeNode* cur = NULL;
int ans = 0;
while(!treeq.empty())
{
int sz = treeq.size();
++ans;
while(sz--)
{
cur = treeq.front();
treeq.pop();
if(cur->left)
treeq.push(cur->left);
if(cur->right)
treeq.push(cur->right);
}
}
return ans;
}
};