一:若只有一个根节点,看概念定义为 0层还是1层
以下代码均定义为1层 即只有一个根节点时候,树的高度为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;
int left=TreeDepth(pRoot->left);
int right=TreeDepth(pRoot->right);
return (left>right?left:right)+1;
}
};
非递归实现:
class Solution {
public:
int TreeDepth(TreeNode* pRoot)
{
queue<TreeNode *>q;
if(pRoot==NULL)
return 0;
q.push(pRoot);
int depth=0;
while(!q.empty())
{
int len=q.size();