題目
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.
java實現
public int run(TreeNode root) {
if (root == null)//空樹深度爲0
return 0;
if (root.left == null && root.right == null)//只有一個節點
return 1;
int leftDepth = run(root.left);
int rightDepth = run(root.right);
if (leftDepth == 0)//左子樹深度爲0,返回右子樹深度加1
return rightDepth + 1;
else if (rightDepth == 0)
return leftDepth + 1;
else
return Math.min(leftDepth, rightDepth) + 1;
}