本文共 1654 字,大约阅读时间需要 5 分钟。
为了解决从根节点到最近叶子节点的最小深度问题,我们可以使用广度优先搜索(BFS)来遍历二叉树。广度优先搜索能够逐层访问每个节点,并记录每个节点到根节点的深度,从而找到离根节点最近的叶子节点的最小深度。
这种方法确保我们能够找到离根节点最近的叶子节点,从而得到最小深度。
import java.util.*;class Solution { public int minDepth(TreeNode root) { if (root == null) { return 0; } int minDepth = Integer.MAX_VALUE; Queue queue = new LinkedList<>(); queue.add(new NodePair(root, 1)); while (!queue.isEmpty()) { NodePair currentPair = queue.poll(); TreeNode current = currentPair.node; int currentDepth = currentPair.depth; if (current.left == null && current.right == null) { if (currentDepth < minDepth) { minDepth = currentDepth; } } else { if (current.left != null) { queue.add(new NodePair(current.left, currentDepth + 1)); } if (current.right != null) { queue.add(new NodePair(current.right, currentDepth + 1)); } } } return minDepth; } private static class NodePair { TreeNode node; int depth; NodePair(TreeNode node, int depth) { this.node = node; this.depth = depth; } }} 这种方法确保了在最坏情况下也能高效地找到最小深度,适用于大规模树结构。
转载地址:http://uvhdz.baihongyu.com/