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.
这道题因为不仔细的缘故两次过,与Maximum Depth of Binary Tree问题类似,区别在于这个问题中,如果一个节点左子树为空、右子树有值,则该节点的深度应取决于右子树,而不能直接取min{左,右}
Recursive:
1 public int minDepth(TreeNode root) { 2 if(root == null) 3 return 0; 4 if(root.left == null) 5 return minDepth(root.right)+1; 6 if(root.right == null) 7 return minDepth(root.left)+1; 8 return Math.min(minDepth(root.left),minDepth(root.right))+1; 9 }
Iterative:
1 public int minDepth(TreeNode root) { 2 if(root == null) 3 return 0; 4 LinkedList queue = new LinkedList(); 5 int curNum = 0; 6 int lastNum = 1; 7 int level = 1; 8 queue.offer(root); 9 while(!queue.isEmpty()) 10 { 11 TreeNode cur = queue.poll(); 12 if(cur.left==null && cur.right==null) 13 return level; 14 lastNum--; 15 if(cur.left!=null) 16 { 17 queue.offer(cur.left); 18 curNum++; 19 } 20 if(cur.right!=null) 21 { 22 queue.offer(cur.right); 23 curNum++; 24 } 25 if(lastNum==0) 26 { 27 lastNum = curNum; 28 curNum = 0; 29 level++; 30 } 31 } 32 return 0; 33 }