题解 | #二叉树的最大深度#(层次 || 递归)
二叉树的最大深度
http://www.nowcoder.com/practice/8a2b2bf6c19b4f23a9bdb9b233eefa73
递归时间复杂度为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;
}
};