package bfs; import java.util.LinkedList; import java.util.Queue; public class TreeMinDepth { /** * 定义TreeNode */ private static class TreeNode { int val; TreeNode left; TreeNode right; TreeNode(int x) { val = x; } } // 二叉树最小深度 int minDepth(TreeNode root) { if (root == null) { return 0; } Queue<TreeNode> q = new LinkedList<>(); q.offer(root); // root != null int depth = 1; while (q.size() > 0) { for (int i = 0; i < q.size(); i++) { TreeNode cur = q.poll(); // 叶子节点 if (cur.left == null && cur.right == null) { return depth; } if (cur.left != null) { q.offer(cur.left); } if (cur.right != null) { q.offer(cur.right); } } depth++; } return depth; } }
原文:https://www.cnblogs.com/zhwcs/p/13706321.html