1.題目:給定一棵二叉樹,求其最大深度/最小深度
最大深度:
最大深度是從根節點到最近葉子節點的最長路徑上的節點數量。
最小深度:
最小深度是從根節點到最近葉子節點的最短路徑上的節點數量。
2.題目分析:
最大深度:返回3
(1)如果二叉樹爲空,則返回0;
(2)如果二叉樹不爲空,則遞歸計算根結點的左孩子、右孩子的深度,取出最大值,然後+1就是該二叉樹的最大深度;
最小深度:返回2
(1)如果二叉樹爲空,則返回0;
(2)如果二叉樹沒有右(左)孩子,則二叉樹最小深度 = 左(右)孩子深度+1;
3.程序設計
遞歸思想
4.程序源代碼
public class TreeDepth {
//取得二叉樹的最大深度
public int maxDepth(TreeNode root){
if(root == null){
return 0;
}
return Math.max(maxDepth(root.left),maxDepth(root.right))+1;
}
//取得二叉樹的最小深度
public int minDepth(TreeNode root) {
if(root == null){
return 0;
}
if(root.left == null){
return minDepth(root.right)+1;
}
if(root.right == null){
return minDepth(root.left)+1;
}
return Math.min(minDepth(root.left),minDepth(root.right))+1;
}
}