抱歉,您的浏览器无法访问本站
本页面需要浏览器支持(启用)JavaScript
了解详情 >

给定一个二叉树 root ,返回其最大深度。

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


思路

  • 层序遍历,每次遍历一层后,depth 计数加 1。

学习点

代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
class Solution {
public:
int maxDepth(TreeNode* root) {
int depth = 0;
queue<TreeNode*> qe;
if (root)
qe.push(root);
while (!qe.empty())
{
int node_num = qe.size();
for (int i = 0; i < node_num; i++)
{
auto tmp = qe.front();
qe.pop();

if (tmp->left)
qe.push(tmp->left);
if (tmp->right)
qe.push(tmp->right);
}
++depth;
}

return depth;
}
};