解法1:递归
思路:
当前节点的深度 = 左子和右子深度的最大值 + 1
复杂度:
●时间:O(N)
●空间:O(N)
代码:
class Solution {
public:
int maxDepth(TreeNode* root) {
if(root == NULL)
return 0;
return max(maxDepth(root->left), maxDepth(root->right)) + 1;
}
};
解法2:层序遍历
思路:
求二叉树的深度 = 求二叉树有多少层,所以用层序遍历就好了
复杂度:
●时间:O(N)
●空间:O(N),当树平衡时,队列queue同时存储N/2个节点。
代码:
class Solution {
public:
int maxDepth(TreeNode* root) {
if(root == NULL)
return 0;
queue<TreeNode*>my_queue;
my_queue.push(root);
int ans = 0;
while(!my_queue.empty()){
//用size控制每层
int size = my_queue.size();
while(size--){
TreeNode* cur = my_queue.front();
my_queue.pop();
if(cur->left != NULL)
my_queue.push(cur->left);
if(cur->right != NULL)
my_queue.push(cur->right);
}
//每层ans + 1
ans++;
}
return ans;
}
};