二叉树的深度
输入一棵二叉树,求该树的深度。从根节点到叶节点依次经过的结点(含根、叶节点)形成树的一条路径,最长路径的长度为树的深度。
题解:
针对此题,有多种解法,下面介绍其中两种。
1)递归法:
通过递归,来不断计算最长路径,代码如下:
/*
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){
int depth;
if(!pRoot) return 0;
int left=TreeDepth(pRoot->left);
int right=TreeDepth(pRoot->right);
depth=max(left,right);
return depth+1;
}
}
2)层次遍历法
将每层的节点数存入队列中。即一层一层的将每层的节点数都送入队列,每输出一层节点,就送入该层的下一层节点。最后得到节点数。
/*
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){
/*int depth;
if(!pRoot) return 0;
int left=TreeDepth(pRoot->left);
int right=TreeDepth(pRoot->right);
depth=max(left,right);
return depth+1;*/
queue<TreeNode*> q1;//每层的节点
queue<int> q2;//每层节点数量
if(!pRoot) return 0;
q1.push(pRoot);//存入根节点
q2.push(1);//根节点数为1个
int depth=0;
while(q1.size()!=0){
TreeNode *p;
int temp1,temp2;
temp1=q2.front();//获得每层的节点数量
q2.pop();
temp2=0;
depth++;
while(temp1){//输出每层的节点,并送入该层的子节点
p=q1.front();
q1.pop();
if(p->left){
q1.push(p->left);
temp2++;}
if(p->right) {
q1.push(p->right);
temp2++;}
temp1--;//输出完该层所有节点,压入该层的节点数
if(!temp1)
q2.push(temp2);
}
}
return depth;
}
};