Question:
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.
1、题型分类:
2、思路:利用set存储深度,递归查询,需要注意的是需要将深度的递增放在外面,不能放在函数里面,比如
depath(node.left, set, nodeDepth++);
depath(node.right, set, nodeDepth++);
这样会使深度错误。
3、时间复杂度:
4、代码:
public int minDepth(TreeNode root) { if(root==null) return 0; SortedSet<Integer> set=new TreeSet<Integer>(); depath(root, set, 1); return set.first(); } public void depath(TreeNode node,Set<Integer> set,int nodeDepth) { if(node.left==null && node.right==null) {set.add(nodeDepth);return;}; nodeDepth++; if(node.left!=null) depath(node.left, set, nodeDepth); if(node.right!=null) depath(node.right, set, nodeDepth); }
5、优化:
6、扩展: