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.
public int minDepth(TreeNode root) {
/**
* 求树的最小深度
* 采用分治法
* 1.将大问题分成子问题,分别进行求解
* 2.将子问题合并成大问题的解
*/
if (root == null) {
return 0;
}
//divide步,分别求解子树的最小深度
int right = minDepth(root.right);
int left = maxDepth(root.left);
//merge步,根据子树的最小深度,求解
if (right == 0 || left == 0) {
return right == 0 ? left : right;
}
return Math.min(minDepth(root.right), minDepth(root.left)) + 1;
}