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.
給定二叉樹而昨,找出它的最小深度锅铅。最小深度是沿從根節(jié)點到最近葉節(jié)點的最短路徑的節(jié)點數(shù)躏筏。
Java版本
public int run(TreeNode node) {
if(node == null)
return 0;
if(node.left == null && node.right == null)
return 1;
if(node.left == null)
run(node.right) + 1;
if(node.right == null)
run(node.left) + 1;
return Math.min(run(node.left), run(right));
}
算法解釋:
整體采用遞歸算法树瞭,以根節(jié)點為起始點,分別算出左右孩子的最大深度拯勉,然后取出其最小值豹障。
代碼解釋:
如果一個節(jié)點的左右孩子都為null,則此節(jié)點為葉子節(jié)點宿接,所以其深度為1赘淮。
if(node.left == null && node.right == null)
return 1;
如果一個節(jié)點的左孩子為空,則計算其右孩子的深度睦霎,并返回最小值梢卸。
因為所有的節(jié)點都算一個深度值,所以要加1.
if(node.left == null)
run(node.right) + 1;
if(node.right == null)
run(node.left) + 1;