题目:
Calculate the depth of Binary Tree.
Code:
class Solution{
//树的最大深度
public int getMaxDep(Node root){
if(root == null) return 0;
return Math.max(getMaxDep(root.left), getMaxDep(root.right))+1;
}
//树的最小深度
public int getMinDep(Node root){
if(root == null) return 0;
int l = getMinDep(root.left)+1;
int r = getMinDep(root.right)+1;
if(root.left!=null && root.right!=null) return Math.min(l, r);
else return Math.max(l, r);
}
}
总结:
最大深度不必多说,最小深度和LCA的结构类似,用的是bottom-up的结构。