111. 二叉树的最小深度
111. 二叉树的最小深度
https://leetcode-cn.com/problems/minimum-depth-of-binary-tree/description/
package com.test; import java.util.ArrayList; import java.util.List; /** * @Author stono * @Date 2018/9/3 上午8:06 */ public class Lesson111 { public static void main(String[] args) { TreeNode t1 = new TreeNode(1); TreeNode t2L = new TreeNode(2); TreeNode t2R = new TreeNode(2); TreeNode t3_1 = new TreeNode(3); TreeNode t3_2 = new TreeNode(4); TreeNode t3_3 = new TreeNode(4); TreeNode t3_4 = new TreeNode(3); t1.left = t2L; t1.right = t2R; t2L.left = t3_1; t2L.right = t3_2; t2R.left = t3_3; t2R.right = t3_4; int i = minDepth(t1); System.out.println(i); } public static int minDepth(TreeNode root) { if (root == null) { return 0; } List<Integer> list = new ArrayList<>(8); minDepth(1, root, list); int min = list.get(0); for (int i = 1; i < list.size(); i++) { if (list.get(i) < min) { min = list.get(i); } } return min; } /** * 把中间的结果都进行缓存 * @param i * @param root * @param list */ private static void minDepth(int i, TreeNode root, List<Integer> list) { // 叶子节点的情况 if (root.left == null && root.right == null) { list.add(i); } else { if (root.left != null) { minDepth(i + 1, root.left, list); } if (root.right != null) { minDepth(i + 1, root.right, list); } } } }