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.
int min = Integer.MAX_VALUE;
public int minDepth(TreeNode root) {
if (root == null) {
return 0;
}
helper(root, 1);
return min;
}
private void helper(TreeNode root, int depth) {
if (root.left == null && root.right == null) {
min = Math.min(min, depth);
}
if (root.left != null) {
helper(root.left, depth + 1);
}
if (root.right != null) {
helper(root.right, depth + 1);
}
}
或者:
public static int minDepth(TreeNode root) {
if (root == null) return 0;
if (root.left == null) return minDepth(root.right) + 1;
if (root.right == null) return minDepth(root.left) + 1;
return Math.min(minDepth(root.left),minDepth(root.right)) + 1;
}
或者level order更好
求max depth:
public int findHeight(TreeNode root) {
if (root == null) {
return 0;
}
return Math.max(findHeight(root.left), findHeight(root.right)) + 1;
}