题目描述
输入一棵二叉树,求该树的深度。从根结点到叶结点依次经过的结点(含根、叶结点)形成树的一条路径,最长路径的长度为树的深度。
示例1
输入
复制
{1,2,3,4,5,#,6,#,#,7}
返回值
复制
4
(我)①想到层次遍历,每进入一层就count++,代码长。
/*
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 count=0;
queue<TreeNode*> que;
if(pRoot==NULL) return 0;
que.push(pRoot);
while(!que.empty())
{
count++;
int n=que.size();
for(int i=0;i<n;i++)
{
if(que.front()->left) que.push(que.front()->left);
if(que.front()->right) que.push(que.front()->right);
que.pop();
}
}
return count;
}
};
②取max左和右子树,直接递归,并+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) {
if(pRoot==NULL) return 0;
return 1+max(TreeDepth(pRoot->left), TreeDepth(pRoot->right));
}
};
再简洁一点可以写成一句话:
/*
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) {
return pRoot==NULL?0:(1+max(TreeDepth(pRoot->left), TreeDepth(pRoot->right)));
}
};