import java.util.*; /* * public class TreeNode { * int val = 0; * TreeNode left = null; * TreeNode right = null; * public TreeNode(int val) { * this.val = val; * } * } */ /** * NC234 二叉树的最小深度 * @author d3y1 */ public class Solution { private int result = Integer.MAX_VALUE; /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * * @param root TreeNode类 * @return int整型 */ public int run (TreeNode root) { return solution1(root); // return solution2(root); } /** * bfs * @param root * @return */ private int solution1(TreeNode root){ if(root == null){ return 0; } levelOrder(root); return result; } /** * 层序遍历: 队列 * @param root */ private void levelOrder(TreeNode root){ if(root == null){ return; } Queue<QueueNode> queue = new LinkedList<>(); queue.offer(new QueueNode(root, 1)); QueueNode queueNode; while(!queue.isEmpty()){ queueNode = queue.poll(); if(queueNode.node != null){ // 叶子节点 if(queueNode.node.left==null && queueNode.node.right==null){ result = queueNode.depth; break; } if(queueNode.node.left != null){ queue.offer(new QueueNode(queueNode.node.left, queueNode.depth+1)); } if(queueNode.node.right != null){ queue.offer(new QueueNode(queueNode.node.right, queueNode.depth+1)); } } } } /** * dfs * @param root * @return */ private int solution2(TreeNode root){ if(root == null){ return 0; } postOrder(root, 1); return result; } /** * 后序遍历: 递归 * @param root * @param depth */ private void postOrder(TreeNode root, int depth){ if(root == null){ return; } if(depth < result){ postOrder(root.left, depth+1); postOrder(root.right, depth+1); // 当前节点叶子节点 if(root.left==null && root.right==null){ result = depth; } } } /** * 队列节点 */ private class QueueNode { TreeNode node; int depth; public QueueNode(TreeNode node, int depth){ this.node = node; this.depth = depth; } } }