CodingInterview-二叉树的深度

如果用递归的化思路非常简单,也只需将树遍历一遍。代码如下所示:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
/*
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 lDepth=this->TreeDepth(pRoot->left);
int rDepth=this->TreeDepth(pRoot->right);
return 1+(lDepth>rDepth?lDepth:rDepth);
}
};

如果不使用递归的话,可能就稍微麻烦一些,需要使用队列进行层序遍历,每遍历一层就让层数 +1。

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
/*
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;
queue<TreeNode*> q;
q.push(pRoot);
int depth=0;
int lastNum=1,num=0;
while(!q.empty()){
TreeNode* t=q.front();
q.pop();
if(t->left!=NULL){
q.push(t->left);
num++;
}
if(t->right!=NULL){
q.push(t->right);
num++;
}
lastNum--;
if(lastNum==0){
depth++;
lastNum=num;
num=0;
}
}
return depth;
}
};