最大深度
非递归方法:
Queue<TreeNode> que = new LinkedList<TreeNode>();
que.add(root);
int max_high = 0;
while(!que.isEmpty()){
int m = que.size();
for(int i= 0;i<m;i++){
TreeNode node=que.poll();
if(node.left!=null){
que.add(node.left);
}
if(node.right!=null){
que.add(node.right);
}
}
max_high++;
}
return max_high;
递归方法:
class Solution {
public int maxDepth(TreeNode root) {
if(root==null){
return 0;
}
int left = maxDepth(root.left);
int right = maxDepth(root.right);
return Math.max(left,right)+1;
}
}
最小深度
class Solution {
public int minDepth(TreeNode root) {
if(root==null) return 0;
int left = minDepth(root.left);
int right = minDepth(root.right);
return (left!=0&&right!=0) ? 1+Math.min(left,right):1+left+right;
}
}