递归时间复杂度为O(nlog2n)
class Solution {
public:
int maxDepth(TreeNode* root) {
if(!root) return 0;
return max(maxDepth(root->left),maxDepth(root->right)) + 1;
}
};
层次遍历的时间复杂度O(n)
class Solution {
public:
int maxDepth(TreeNode* root) {
if(!root) return 0;
queue<TreeNode*> q;
q.push(root);
int dept = 0;
while(!q.empty()){
dept++;
int size = q.size();
while(size--){
TreeNode *tmp = q.front();
q.pop();
if(tmp->left) q.push(tmp->left);
if(tmp->right) q.push(tmp->right);
}
}
return dept;
}
};
京公网安备 11010502036488号