BFS
import java.util.*;
public class Solution {
public int run (TreeNode root) {
if(root == null){
return 0;
}
Queue q = new LinkedList();
q.add(root);
int depth = 1;
while(!q.isEmpty()){
int size = q.size();
for(int i = 0;i<size;i++){
TreeNode cur = q.poll();
if(cur.left == null && cur.right == null){
return depth;
}
if(cur.left != null){
q.add(cur.left);
}
if(cur.right != null){
q.add(cur.right);
}
}
depth++;
}
return depth;
}
}
京公网安备 11010502036488号