1.BFS
class Solution {
public:
int maxDepth(TreeNode* root) {
queue<TreeNode*> q;
int count=0;
if(root==nullptr) return 0;
q.push(root);
while(!q.empty()){
int n=q.size();
for(int i=0;i<n;++i){
TreeNode* node=q.front();
q.pop();
if(node->left!=nullptr){
q.push(node->left);
}
if(node->right!=nullptr){
q.push(node->right);
}
}
count++;
}
return count;
}
};
2.DFS
DFS是真np,两行就没了
class Solution {
public:
int maxDepth(TreeNode* root) {
if(root==nullptr) return 0;
return max(maxDepth(root->left),maxDepth(root->right))+1;
}
};