求树的最小深度
1 package algo; 2 3 import java.util.LinkedList; 4 import java.util.Queue; 5 import java.lang.Math; 6 7 /* 8 * Description: 9 * Given a binary tree, find its minimum depth.The minimum depth is the number of 10 * nodes along the shortest path from the root node down to the nearest leaf node. 11 */ 12 class TreeNode { 13 int val; 14 TreeNode left; 15 TreeNode right; 16 17 TreeNode(int x) { 18 val = x; 19 } 20 } 21 22 public class Minimum_depth_of_binary_tree { 23 /* 24 * 非递归,广度优先遍历,通过队列遍历每层节点,遇到的第一个叶节点即为最小深度的叶节点。 25 */ 26 public static int run(TreeNode root) { 27 int minDepth = 0; 28 Queue<TreeNode> q = new LinkedList<TreeNode>(); 29 if (root != null) { 30 q.offer(root); 31 } 32 while (!q.isEmpty()) { 33 int len = q.size(); 34 minDepth++; 35 for (int i = 0; i < len; i++) { 36 TreeNode tmp = q.poll(); 37 if (tmp.left != null) { 38 q.offer(tmp.left); 39 } 40 if (tmp.right != null) { 41 q.offer(tmp.right); 42 } 43 if (tmp.left == null && tmp.right == null) { 44 return minDepth; 45 } 46 } 47 } 48 return minDepth; 49 } 50 51 /* 52 * 递归,深度优先遍历,问题可以归结为:当前节点下最小深度=min(左子树最小深度,右子树最小深度)+1 53 * 递归终止条件为root==null。 54 */ 55 public static int run_1(TreeNode root) { 56 if (root == null) { 57 return 0; 58 } 59 int l = run_1(root.left); 60 int r = run_1(root.right); 61 if (l == 0 || r == 0) { 62 return l + r + 1; 63 } 64 return 1 + Math.min(l, r); 65 } 66 67 public static void main(String[] args) { 68 TreeNode treeNode = new TreeNode(1); 69 treeNode.left = new TreeNode(2); 70 treeNode.left.left = new TreeNode(3); 71 treeNode.left.left.left = new TreeNode(4); 72 System.out.println(Minimum_depth_of_binary_tree.run(treeNode)); 73 System.out.println(Minimum_depth_of_binary_tree.run_1(treeNode)); 74 } 75 }
运行结果:
4
4
灵活专注,不骄不躁。
浙公网安备 33010602011771号