题目描述
输入一棵二叉树,求该树的深度。从根结点到叶结点依次经过的结点(含根、叶结点)形成树的一条路径,最长路径的长度为树的深度。
AC C++ Solution:
递归
class Solution {
public:
int TreeDepth(TreeNode* pRoot)
{
if(pRoot == NULL)
return 0;
return max(TreeDepth(pRoot->left),TreeDepth(pRoot->right)) + 1;
}
};
非递归:
class Solution {
public:
int TreeDepth(TreeNode* pRoot)
{
if(pRoot == nullptr)
return 0;
queue<TreeNode*> q;
q.push(pRoot);
int level = 0;
while(!q.empty()) {
int n = q.size();
level++;
while(n--) {
TreeNode* node = q.front();
q.pop();
if(node->left)
q.push(node->left);
if(node->right)
q.push(node->right);
}
}
return level;
}
};