104. 二叉树的最大深度(C++题解含VS可运行源程序)
1.题解
1.方法一:DFS深度优先搜索(递归)
- 二叉树的最大深度 = max(左子树深度 + 右子树深度) + 1
- 只考虑根节点是否为空,其余交给递归处理
2.方法二:BFS广度优先遍历
- 广度优先遍历使用队列,树的节点逐层添加到队列。
- 队列中只保存一层节点
2.力扣C++源码
1.方法一:DFS深度优先搜索(递归)
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
int maxDepth(TreeNode* root) {
if (root == NULL) return 0;
return max(maxDepth(root->left), maxDepth(root->right)) + 1;
}
};
2.方法二:BFS广度优先遍历
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
int maxDepth(TreeNode* root) {
if (root == NULL) return 0;
queue<TreeNode*> Q;
Q.push(root);
int depth = 0;
while (!Q.empty()) {
int levelSize = Q.size