LeetCode(104):二叉树的最大深度

时间:2021-05-10 12:29:40

Easy!

题目描述:

给定一个二叉树,找出其最大深度。

二叉树的深度为根节点到最远叶子节点的最长路径上的节点数。

说明: 叶子节点是指没有子节点的节点。

示例:
给定二叉树 [3,9,20,null,null,15,7]

    3
/ \
9 20
/ \
15 7

返回它的最大深度 3 。

解题思路:

求二叉树的最大深度问题用到深度优先搜索DFS递归的完美应用,跟求二叉树的最小深度问题原理相同。

C++解法一:

 class Solution {
public:
int maxDepth(TreeNode* root) {
if (!root) return ;
return + max(maxDepth(root->left), maxDepth(root->right));
}
};

我们也可以使用层序遍历二叉树,然后计数总层数,即为二叉树的最大深度。

C++解法二:

 class Solution {
public:
int maxDepth(TreeNode* root) {
if (!root) return ;
int res = ;
queue<TreeNode*> q;
q.push(root);
while (!q.empty()) {
++res;
int n = q.size();
for (int i = ; i < n; ++i) {
TreeNode *t = q.front(); q.pop();
if (t->left) q.push(t->left);
if (t->right) q.push(t->right);
}
}
return res;
}
};