1 /** 2 * Definition for binary tree 3 * public class TreeNode { 4 * int val; 5 * TreeNode left; 6 * TreeNode right; 7 * TreeNode(int x) { val = x; } 8 * } 9 */ 10 public class Solution { 11 public int minDepth(TreeNode root) { 12 // IMPORTANT: Please reset any member data you declared, as 13 // the same Solution instance will be reused for each test case. 14 LinkedList<TreeNode> visiting = new LinkedList<TreeNode>(); 15 LinkedList<TreeNode> next = new LinkedList<TreeNode>(); 16 int count = 1; 17 if(root == null) 18 return 0; 19 visiting.add(root); 20 while(!visiting.isEmpty()){ 21 while(!visiting.isEmpty()){ 22 TreeNode tmp = visiting.poll(); 23 if(tmp.left == null && tmp.right == null) 24 return count; 25 if(tmp.left!=null) 26 next.add(tmp.left); 27 if(tmp.right!=null) 28 next.add(tmp.right); 29 } 30 visiting.addAll(next); 31 next.clear(); 32 count++; 33 } 34 return 0; 35 } 36 }
【推荐】还在用 ECharts 开发大屏?试试这款永久免费的开源 BI 工具!
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步