題目: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.
翻譯:
給定一個(gè)二叉樹,找到其最小深度愉阎。最小深度是從根節(jié)點(diǎn)到最近葉節(jié)點(diǎn)的最短路徑的節(jié)點(diǎn)數(shù)洞慎。
解題思路:要找二叉樹最小深度稚失,那么只要判斷根節(jié)點(diǎn)左右兩邊的子樹的最小深度慌植,然后又可以把左右子樹在分成左右子樹,依次類推就可以把問題分解状植。運(yùn)用遞歸优炬,每次遞歸一次就加一,直到找到葉節(jié)點(diǎn)境蔼。
/**
* Definition for binary tree
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public int run(TreeNode root) {
if(root == null)
return 0;
int l = run(root.left);
int r = run(root.right);
if(l==0 || r==0)
return 1+l+r;
return 1+Math.min(l,r);
}
}
注意:本題要注意最小深度與最大深度的區(qū)別:對(duì)于最大深度灶平,不需要考慮當(dāng)前子樹是否為單子樹(即一側(cè)子樹深度為0)的情況伺通,即最大深度一直等于左右子樹的最大值;對(duì)于最小深度逢享,需要考慮當(dāng)前子樹是否為單子樹的情況罐监,對(duì)于雙子樹,其最小深度為左右子樹的最小值瞒爬,對(duì)于單子樹弓柱,其最小深度為左右深度的最大值(因?yàn)橛幸粋?cè)的子樹為0)。