描述
给定一个二叉树,找出其最大深度。
二叉树的深度为根节点到最远叶子节点的最长路径上的节点数。
说明: 叶子节点是指没有子节点的节点。
示例:
给定二叉树 [3,9,20,null,null,15,7],
3
/ \
9 20
/ \
15 7
返回它的最大深度 3 。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/maximum-depth-of-binary-tree/
解答,递归实现
class Solution {
public:
// 递归求解,深度优先遍历
int maxDepth_recur(TreeNode *root) {
if (root == nullptr) {
return 0;
}
return std::max(maxDepth_recur(root->left) + 1, maxDepth_recur(root->right) + 1);
}
// 迭代求解,广度优先遍历,最后一个叶子节点的深度
int maxDepth(TreeNode *root) {
if(root == nullptr) {
return 0;
}
int max_depth = 0;
std::queue<std::pair<TreeNode *, int>> q;
q.emplace(root, 1);
while (!q.empty()) {
auto p = q.front();
q.pop();
if (p.first->left == nullptr && p.first->right == nullptr) {
// 层序遍历中,最后一个叶子节点的深度即为最大深度,因此每次取得叶子节点赋值即可
max_depth = p.second;
}
if (p.first->left) {
q.emplace(p.first->left, p.second + 1);
}
if (p.first->right) {
q.emplace(p.first->right, p.second + 1);
}
}
return max_depth;
}
};