一、剑指 Offer 55 - I. 二叉树的深度
地址
class Solution {
public int maxDepth(TreeNode root) {
if(root==null){
return 0;
}
int left=maxDepth(root.left);
int right=maxDepth(root.right);
return 1+Math.max(left,right);
}
}
二、剑指 Offer 55 - II. 平衡二叉树
地址
class Solution {
public boolean isBalanced(TreeNode root) {
if(root==null||(root.left==null&&root.right==null)){
return true;
}
int leftMax=maxDepth(root.left);
int rightMax=maxDepth(root.right);
return Math.abs(leftMax-rightMax)<=1&&isBalanced(root.left)&&isBalanced(root.right);
}
private int maxDepth(TreeNode node){
if(node==null){
return 0;
}
return 1+Math.max(maxDepth(node.left),maxDepth(node.right));
}
}