递归
class Solution {
public:
int TreeDepth(TreeNode* pRoot) {
if(pRoot == NULL)
{
return 0;
}
if(pRoot->left == NULL && pRoot->right == NULL)
{
return 1;
}
return max(maxD,max(1+TreeDepth(pRoot->left),1+TreeDepth(pRoot->right)));//每次要+跟节点
}
int maxD = -1;
};
遍历
class Solution {
public:
int TreeDepth(TreeNode* pRoot) {
if(pRoot == NULL)
{
return 0;
}
int maxD = 0;
//层次遍历
queue<TreeNode* > q;
q.push(pRoot);
while(!q.empty())
{
int n = q.size();
for(int i = 0;i<n;i++)
{
TreeNode *node = q.front();
q.pop();
if(node->left)
{
q.push(node->left);
}
if(node->right)
{
q.push(node->right);
}
}
maxD++;
}
return maxD;
}
};