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.
问题:判断一棵二叉树是否为平衡二叉树,所谓平衡二叉树指左右子树的高度相差不超过1
思想:递归,利用104题的maxDepth函数计算树的高度,但是要满足左右子树均高度平衡的情况下本二叉树才是平衡二叉树
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ public class Solution { public boolean isBalanced(TreeNode root) { if(root==null) return true; int leftdepth=maxDepth2(root.left); int rightdepth=maxDepth2(root.right); if(Math.abs(leftdepth-rightdepth)>1) return false; boolean left=isBalanced(root.left);//****** boolean right=isBalanced(root.right); return left&&right; } public int maxDepth2(TreeNode root){ int depth=0; if(root==null) return 0; depth++; int left=maxDepth2(root.left); int right=maxDepth2(root.right); depth+=Math.max(left, right); return depth; } }