题目链接:https://leetcode.com/problems/minimum-depth-of-binary-tree/
题目:
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:
int min = Integer.MAX_VALUE; //此处有bug 不过ac还是没问题的
public int minDepth(TreeNode root) {
if (root == null) {
return 0;
}
findPath3(root, 0);
return min;
}
public void findPath3(TreeNode p, int length) {
if (p.left == null && p.right == null) {
length++;
if (length < min)
min = length;
}
if (p.left != null)
findPath3(p.left, length + 1);
if (p.right != null)
findPath3(p.right, length + 1);
}
算法2:
public int minDepth(TreeNode root) {
if(root==null)
return 0;
if(root.left==null){//当左子树为空时,不能选择左(此时为0)右子树深度来比较最小深度,而要以右子树深度
return minDepth(root.right)+1;
}
if(root.right==null){
return minDepth(root.left)+1;
}
return Math.min(minDepth(root.left),minDepth(root.right))+1;
}