方法一: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;
}
};
文章介绍了两种计算二叉树最大深度的方法:深度优先搜索(DFS)和广度优先搜索(BFS)。DFS方法的时间复杂度为O(N),空间复杂度为O(height);BFS方法同样具有O(N)的时间复杂度,但空间复杂度与每层数目(用queue表示)相关,为O(x)。
271

被折叠的 条评论
为什么被折叠?



