Given a binary tree, find its minimum depth.
The minimum depth is the number of nodes along the shortest path from the root node down to the nearest leaf node.
public class Solution { public int minDepth(TreeNode root) { if(root == null) return 0; return minDepth(root, 1); } private int minDepth(TreeNode root, int depth) { if(root == null) return Integer.MAX_VALUE; if(root.left == null && root.right == null) return depth; int leftMinDepth = minDepth(root.left, depth+1); int rightMinDepth = minDepth(root.right, depth+1); return Math.min(leftMinDepth, rightMinDepth); } }
public class Solution { public int minDepth(TreeNode root) { if(root == null) return 0; else { if(root.left != null && root.right != null) return 1 + Math.min(minDepth(root.left), minDepth(root.right)); else return 1 + minDepth(root.right) + minDepth(root.left); } } }
mistakes: when only one child, add the child seperately
public class Solution { public int minDepth(TreeNode root) { if (root == null) return 0; int depth = 0; Queue<TreeNode> que = new LinkedList<TreeNode>(); que.offer(root); que.offer(null); while (!que.isEmpty()) { TreeNode cur = que.poll(); if (cur == null) { // end of a level ++depth; que.offer(null); } else { if (cur.left == null && cur.right == null) return depth+1; if (cur.left != null) que.offer(cur.left); if (cur.right != null) que.offer(cur.right); } } return depth; } }