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.
Note: A leaf is a node with no children.
Example:
Given binary tree [3,9,20,null,null,15,7],
3
/ \
9 20
/ \
15 7
return its minimum depth = 2.
让找出二叉树的最小深度
思路:
深度的定义是从root到叶子节点的最短路径,注意一定是到叶子节点
比如root只有左子树,没有右子树,这时候不能说最短深度是1,因为root本身不是叶子节点,所以必须是到左子树深度+1
所以当左或右子树为null时,要看另一边子树的深度+1
都不是null时,选最小深度
//0ms
public int minDepth(TreeNode root) {
if (root == null) {
return 0;
}
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;
}
}