<span style="font-family: Arial, Helvetica, sans-serif; background-color: rgb(255, 255, 255);">方法1:递归,返回左子树或右子树加1,然后把这个值当做下次的输入。</span>
class Solution {
public:
int maxDepth(TreeNode *root) {
if(root==NULL)
return 0;
else
{
int l=maxDepth(root->left);
int r=maxDepth(root->right);
return max(l, r)+1;
}
}
};
方法2:遍历
class Solution {
public:
int maxDepth(TreeNode *root)
{
if(root == NULL) return 0;
int res = 0;
queue<TreeNode *> q;
q.push(root);
while(!q.empty())
{
++ res;
for(int i = 0, n = q.size(); i < n; ++ i)
{
TreeNode *p = q.front();
q.pop();
if(p -> left != NULL) q.push(p -> left);
if(p -> right != NULL) q.push(p -> right);
}
}
return res;
}
};