1.深度优先搜索
class Solution {
public:
int maxDepth(TreeNode* root) {
if(root==NULL) return 0;
return 1+max(maxDepth(root->left),maxDepth(root->right));
}
};
2.广度优先搜索
class Solution {
public:
int maxDepth(TreeNode* root) {
if(root==NULL) return 0;
int ans=0;
queue<TreeNode*> Q;
Q.push(root);
int size;
while(!Q.empty()){
size=Q.size();
while(size>0){
TreeNode* p=Q.front();
Q.pop();
if(p->left) Q.push(p->left);
if(p->right) Q.push(p->right);
size-=1;
}
ans++;
}
return ans;
}
};