-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path39_jianzhi_depth.cpp
47 lines (46 loc) · 1.1 KB
/
39_jianzhi_depth.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
/*
struct TreeNode {
int val;
struct TreeNode *left;
struct TreeNode *right;
TreeNode(int x) :
val(x), left(NULL), right(NULL) {
}
};*/
class Solution {
public:
/*int TreeDepth(TreeNode* pRoot)//递归
{
if(pRoot == NULL)
return 0;
int leftlen = TreeDepth(pRoot->left);
int rightlen = TreeDepth(pRoot->right);
return (leftlen > rightlen)? (leftlen+1) : (rightlen+1);
}*/
int TreeDepth(TreeNode* pRoot){//层序遍历
if(pRoot == NULL)
return 0;
queue<TreeNode*> q;
int depth = 0;
q.push(pRoot);
int nextLayerCount = 1;
int count = 0;
while(!q.empty()){
TreeNode* top = q.front();
count++;
q.pop();
if(top->left){
q.push(top->left);
}
if(top->right){
q.push(top->right);
}
if(count == nextLayerCount){
count =0;
nextLayerCount = q.size();
depth++;
}
}
return depth;
}
};