给定一个二叉树,判断它是否是高度平衡的二叉树。 本题中,一棵高度平衡二叉树定义为: 一个二叉树每个节点 的左右两个子树的高度差的绝对值不超过1。 示例 1: 给定二叉树 [3,9,20,null,null,15,7] 3 / \ 9 20 / \ 15 7 返回 true 。 示例 2: 给定二叉树 [1,2,2,3,3,null,null,4,4] 1 / \ 2 2 / \ 3 3 / \ 4 4 返回 false 。
depth() 来求二叉树的深度null,是则说明该树是平衡树public boolean isBalanced(TreeNode root) {
// 判断根节点是否为 null,是则该树是平衡
if (root == null) {
return true;
}
// 若二叉树左右子树高度差大于 1,则说明该树不平衡
if (Math.abs(depth(root.left) - depth(root.right)) > 1) {
return false;
}
// 递归左右子树,判断是否均为平衡树
return isBalanced(root.left) && isBalanced(root.right);
}
// 求一个二叉树的深度
public int depth(TreeNode root) {
if (root == null) {
return 0;
}
return 1 + Math.max(depth(root.left), depth(root.right));
}