|
| 1 | +package easy; |
| 2 | + |
| 3 | +import java.util.LinkedList; |
| 4 | +import java.util.Queue; |
| 5 | + |
| 6 | +import classes.TreeNode; |
| 7 | + |
| 8 | +public class MinimumDepthofBinaryTree { |
| 9 | +/**We can solve this problem using both BFS and DFS: |
| 10 | + * DFS is to visit every single root to leaf path and return the shortest one. |
| 11 | + * BFS is to visit every level and return whenever we find the first leaf node.*/ |
| 12 | + public int minDepth(TreeNode root) { |
| 13 | + if(root == null) return 0; |
| 14 | + int left = minDepth(root.left); |
| 15 | + int right = minDepth(root.right); |
| 16 | + if(left == 0) return right+1; |
| 17 | + if(right == 0) return left+1; |
| 18 | + return Math.min(left, right)+1; |
| 19 | + } |
| 20 | + |
| 21 | + public static void main(String[] args){ |
| 22 | + MinimumDepthofBinaryTree test = new MinimumDepthofBinaryTree(); |
| 23 | + TreeNode root = new TreeNode(1); |
| 24 | + root.left = new TreeNode(2); |
| 25 | + root.right = new TreeNode(3); |
| 26 | + System.out.println(test.minDepth(root)); |
| 27 | + } |
| 28 | + |
| 29 | + |
| 30 | + public int minDepth_BFS(TreeNode root) { |
| 31 | + if(root == null) return 0; |
| 32 | + Queue<TreeNode> q = new LinkedList(); |
| 33 | + q.offer(root); |
| 34 | + int level = 0; |
| 35 | + while(!q.isEmpty()){ |
| 36 | + level++; |
| 37 | + int size = q.size(); |
| 38 | + for(int i = 0; i < size; i++){ |
| 39 | + TreeNode curr = q.poll(); |
| 40 | + if(curr.left != null) q.offer(curr.left); |
| 41 | + if(curr.right != null) q.offer(curr.right); |
| 42 | + if(curr.left == null && curr.right == null) return level; |
| 43 | + } |
| 44 | + } |
| 45 | + return level; |
| 46 | + } |
| 47 | + |
| 48 | + |
| 49 | + |
| 50 | +} |
0 commit comments