解题思路:
题目的意思就是每个节点的左右子树的高度差的绝对值不能超过1,就是平衡二叉树,则满足题目需求;
代码:
publicbooleanisBalanced(TreeNoderoot) { if(root==null){ returntrue; } intleftH=getHeight(root.left); intrightH=getHeight(root.right); returnMath.abs(leftH-rightH)<=1&&isBalanced(root.left) &&isBalanced(root.right); } publicintgetHeight(TreeNoderoot) { if (root==null) { return0; } intleftHeight=getHeight(root.left); intrightHeight=getHeight(root.right); returnleftHeight>rightHeight?leftHeight+1 : rightHeight+1; }