1.1、题目1
剑指 Offer 55 - II. 平衡二叉树
1.2、解法
递归和下一面一题的结合版,abs去绝对值判断两边的差,然后递归isBalanced来遍历二叉树。
1.3、代码
class Solution {
public boolean isBalanced(TreeNode root) {
if (root == null) {
return true;
} else {
return Math.abs(height(root.left) - height(root.right)) <= 1 && isBalanced(root.left) && isBalanced(root.right);
}
}
public int height(TreeNode root) {
if (root == null) {
return 0;
} else {
return Math.max(height(root.left), height(root.right)) + 1;
}
}
}
2.1、题目2
剑指 Offer 55 - I. 二叉树的深度
2.2、解法
这题emmmm,递归,我就不说了,太简单了。
2.3、代码
class Solution {
public int maxDepth(TreeNode root) {
if(root==null) return 0;
return Math.max(maxDepth(root.left)+1,(maxDepth(root.right)+1));
}
}