题目
Given a binary tree, determine if it is height-balanced.
For this problem, a height-balanced binary tree is defined as a binary tree in which the depth of the two subtrees of every node never differ by more than 1.
For this problem, a height-balanced binary tree is defined as a binary tree in which the depth of the two subtrees of every node never differ by more than 1.
思路
首先,理解题目,判断是否为二叉树高度是否平衡的标准是每个节点的左右子树相差不得超过1
其次,理解题目后,很容易想到这是一道典型的递归题目(ps:特别是面试的时候,二叉树和递归联系的特别多,我面试豌豆荚也是考了一个类似的题目)
最后,首先判断根节点的左右子树高度差,相差大于1返回false,相差不大于1则继续递归的测试根节点的左子树和右子树
AC代码
public class BalancedBinaryTree {
static class TreeNode {
public int val;
public TreeNode left;
public TreeNode right;
public TreeNode(int x) {
this.val = x;
}
}
public static boolean isBalanced(TreeNode root) {
if (root == null) return true;
int lh = getHeight(root.left);
int rh = getHeight(root.right);
if (Math.abs(lh - rh) > 1) return false;
return isBalanced(root.left) && isBalanced(root.right);
}
public static int getHeight(TreeNode root) {
if (root == null) return 0;
return Math.max(getHeight(root.left), getHeight(root.right)) + 1;
}
}
吐槽
csdn神马时候才能支持markdown语法编辑博客啊,如果到过年还不支持markdown,果断迁移到segmentfault上了