方法一:dfs
时间复杂度:O(N),空间复杂度:O(height)
class Solution {
public:
int maxDepth(TreeNode* root) {
if(!root) return 0;
return max(maxDepth(root->left),maxDepth(root->right))+1;
}
};
方法二:bfs
用queue保存每一层节点。时间复杂度O(N),空间复杂度O(x)(和每层数目有关)
class Solution {
public:
int depth=0;
queue<TreeNode*> que;
int maxDepth(TreeNode* root) {
if(!root) return depth;
que.push(root->left);
que.push(root->right);
while(!que.empty()){
depth++;
int size = que.size();
for(int i = 0;i<size;i++){
TreeNode* top = que.front();
if(top){
que.push(top->left);
que.push(top->right);
}
que.pop();
}
}
return depth;
}
};