验证一棵树是不是平衡二叉树。
思路:先写一个求树高的函数,然后求左右孩子的高度,左右孩子高度之差绝对值小于1并且左右孩子都是平衡的,那就返回true。
class Solution {
public boolean isBalanced(TreeNode root) {
if (root == null) {
return true;
}
int left = maxDepth(root.left);
int right = maxDepth(root.right);
return Math.abs(left - right) <=1 && isBalanced(root.left) && isBalanced(root.right); }
public int maxDepth(TreeNode root) {
if (root == null) {
return 0;
}
if (root.left == null && root.right == null) {
return 1;
}
int left = maxDepth(root.left);
int right = maxDepth(root.right);
return Math.max(left, right) + 1;
}
}