class Solution {
public int maxDepth(TreeNode root) {
//根节点入队
Queue<TreeNode> queue = new LinkedList<>();
queue.offer(root);
int deep = 0;
//判空
if(root == null){
return deep;
}
//迭代每一层
while (!queue.isEmpty()) {
int size = queue.size();
for (int i = 0; i < size; i++) {
TreeNode curNode = queue.poll();
if (curNode.left != null) {
queue.offer(curNode.left);
}
if (curNode.right != null) {
queue.offer(curNode.right);
}
}
deep++;
}
return deep;
}
}
二叉树遍历这种题,一般都使用Queue来实现
最新推荐文章于 2021-12-10 17:32:16 发布
![](https://img-home.csdnimg.cn/images/20240711042549.png)