题目描述:
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/maximum-depth-of-binary-tree
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
官方题解链接:
https://leetcode-cn.com/problems/maximum-depth-of-binary-tree/solution/er-cha-shu-de-zui-da-shen-du-by-leetcode-solution/
1、递归 DFS
深度为当前节点的深度 + 左右子树深度的最大值
class Solution {
public:
int maxDepth(TreeNode* root) {
if (root == nullptr) {
return 0;
}
return max(maxDepth(root->left), maxDepth(root->right)) + 1;
}
};
2、BFS
class Solution {
public:
int maxDepth(TreeNode* root) {
if (root == nullptr) {
return 0;
}
int rst = 0;
queue<TreeNode*> que;
que.push(root);
while (!que.empty()) {
int len = que.size();
while (len != 0) {
auto temp = que.front();
que.pop();
if (temp->left != nullptr) {
que.push(temp->left);
}
if (temp->right != nullptr) {
que.push(temp->right);
}
len--;
}
rst++;
}
return rst;
}
};