先要理解 BFS 广度优先收寻
二元树 5 阶图
static void Main(string[] args) { MinDepthCalculate(); } public class TreeNode { public int val; public TreeNode left; public TreeNode right; public TreeNode(int val = 0, TreeNode left = null, TreeNode right = null) { this.val = val; this.left = left; this.right = right; } } /// <summary> /// 计算二元树最小深度 /// </summary> /// <exception cref="NotImplementedException"></exception> private static void MinDepthCalculate() { //宣告一个 5 阶 二元树 TreeNode root = new TreeNode(1, new TreeNode(2, new TreeNode(4, new TreeNode(8, new TreeNode(16), new TreeNode(17)), new TreeNode(9, new TreeNode(18), new TreeNode(19))), new TreeNode(5, new TreeNode(10, new TreeNode(20), new TreeNode(21)), new TreeNode(11, new TreeNode(22), new TreeNode(23)))), new TreeNode(3, new TreeNode(6, new TreeNode(12, new TreeNode(24), new TreeNode(25)), new TreeNode(13, new TreeNode(26), new TreeNode(27))), new TreeNode(7, new TreeNode(14, new TreeNode(28), new TreeNode(29)), new TreeNode(15, new TreeNode(30), new TreeNode(31)))) ); int height = MinDepth(root); Console.WriteLine(height); } private static int MinDepth(TreeNode root) { if (root == null) { return 0; } Queue<TreeNode> queue = new Queue<TreeNode>(); queue.Enqueue(root); int depth = 1; while (queue.Count > 0) { // 捕获当前层的节点数量 int levelSize = queue.Count; for (int i = 0; i < levelSize; i++) { // 仅迭代当前层的节点 TreeNode currentNode = queue.Dequeue(); // 检查当前节点是否为叶节点 if (currentNode.left == null && currentNode.right == null) { return depth; } if (currentNode.left != null) { queue.Enqueue(currentNode.left); } if (currentNode.right != null) { queue.Enqueue(currentNode.right); } } // 完成当前层的处理后,增加深度 depth++; } return depth; }