题目总结
给定一个二叉树,找出其最小深度。
最小深度是从根节点到最近叶子节点的最短路径上的节点数量。
说明: 叶子节点是指没有子节点的节点。
总结
dc算是提供一种解题思路吧(逃~)
Sample Code
class Solution {
public static int minDepth(TreeNode root) {
if (root == null) return 0;
return minDepth1(root);
}
public static int minDepth1(TreeNode root) {
if (root == null) return Integer.MAX_VALUE; //把单边没有的单边排除,下面处理两边都没有的
if(root.left == null && root.right ==null) return 1;
int left_height = minDepth1(root.left);
int right_height = minDepth1(root.right);
return Math.min(left_height, right_height) + 1;
}
}
/**第二种**/
class Solution {
public int minDepth(TreeNode root) {
if(root == null){
return 0;
}else if(root.left == null){
return minDepth(root.right) + 1;
}else if(root.right == null){
return minDepth(root.left) + 1;
}else{
return Math.min(minDepth(root.left), minDepth(root.right)) + 1;
}
}
}
Demo Code
class Solution {
List<Integer> list = new ArrayList();
public int minDepth(TreeNode root) {
if(root == null) return 0;
find_add(root, 1);
return Collections.min(list);
}
public void find_add(TreeNode n, int len) {
if(n == null) return;
if(n.left == null && n.right == null) {
list.add(len);
return;
}
find_add(n.left, len+1);
find_add(n.right, len+1);
}
}