[Lc]104二叉树的最大深度
Contents
题目
题解
二叉树结构如下:
//Definition for a binary tree node.
struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
1. 递归法
时间复杂度: $O(N)$
空间复杂度: $O(N)$
class Solution {//这个题就是遍历然后存最大深度。两种方法1. 递归
public:
int maxDepth(TreeNode* root) {
if(!root) return 0;//特殊情况
return max(maxDepth(root->left),maxDepth(root->right))+1;//调用递归,注意要+1
}
};
2. 队列迭代法(BFS)
时间复杂度: $O(N)$
空间复杂度: $O(N)$
class Solution {//这个题就是遍历然后存最大深度。两种方法2. 队列迭代
public:
int maxDepth(TreeNode* root) {
if(!root) return 0;//特殊情况
int level = 0;//定义存层数的变量
queue<TreeNode*> q;//定义队列
q.push(root);//把根节点加入队列
while(!q.empty()){//队列不为空继续迭代
for(int i=q.size(); i>0; i--){//这一块和#102#103一样,就不用存结果了
TreeNode *cur = q.front();q.pop();
if(cur->left) q.push(cur->left);
if(cur->right) q.push(cur->right);
}
level++;//层数+1
}
return level;//返回结果
}
};
Author ChrisHRZ
LastMod 2020-03-17