题目链接
层序遍历
遍历整棵树,当找到一个叶子节点时,直接返回这个叶子节点的深度。
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
public int minDepth(TreeNode root) {
Deque<TreeNode> queue = new LinkedList<TreeNode>();
int depth = 1;
if(root != null){
queue.offer(root);
}else{
return 0;
}
while(!queue.isEmpty()){
int size = queue.size();
for(int i = 0; i < size; i++){
TreeNode node = queue.poll();
if(node.left == null && node.right == null){
return depth;
}
if(node.left != null){
queue.offer(node.left);
}
if(node.right != null){
queue.offer(node.right);
}
if(i == size - 1){
depth++;
}
}
}
return depth;
}
}