4

#yyds干货盘点# LeetCode 热题 HOT 100:二叉树的最大深度

 2 years ago
source link: https://blog.51cto.com/u_13321676/5767510
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

#yyds干货盘点# LeetCode 热题 HOT 100:二叉树的最大深度

精选 原创

灰太狼_cxh 2022-10-18 16:43:59 博主文章分类:leetcode ©著作权

文章标签 子节点 二叉树 最大深度 文章分类 Java 编程语言 阅读数178

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

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

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

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

返回它的最大深度 3 。

代码实现:

class Solution {
public int maxDepth(TreeNode root) {
if (root == null) {
return 0;
}
Queue<TreeNode> queue = new LinkedList<TreeNode>();
queue.offer(root);
int ans = 0;
while (!queue.isEmpty()) {
int size = queue.size();
while (size > 0) {
TreeNode node = queue.poll();
if (node.left != null) {
queue.offer(node.left);
}
if (node.right != null) {
queue.offer(node.right);
}
size--;
}
ans++;
}
return ans;
}
}

Recommend

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK