-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathTreeDepth.cpp
40 lines (40 loc) · 892 Bytes
/
TreeDepth.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
// Solution 1:
class Solution {
public:
int TreeDepth(TreeNode* root)
{
if (root == NULL)
return 0;
int left = TreeDepth(root->left);
int right = TreeDepth(root->right);
return max(left, right) + 1;
}
};
// Solution 2:
class Solution {
public:
int TreeDepth(TreeNode* root)
{
int depth = 0;
if (root == NULL)
return depth;
queue<TreeNode*> q;
q.push(root);
while(!q.empty())
{
int count = q.size();
while(count>0)
{
TreeNode* node = q.front();
q.pop();
if (node->left)
q.push(node->left);
if (node->right)
q.push(node->right);
count--;
}
depth++;
}
return depth;
}
};