import java.util.*; /* * public class TreeNode { * int val = 0; * TreeNode left = null; * TreeNode right = null; * public TreeNode(int val) { * this.val = val; * } * } */ public class Solution { /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * * @param pRoot TreeNode类 * @return bool布尔型 */ public boolean IsBalanced_Solution (TreeNode pRoot) { // write code here // 采用前序遍历,分别求左、右子树的高度 // 然后依次递归左。右子树,看子树是否都是平衡二叉树 if (pRoot == null) { return true; } int left = high(pRoot.left); int right = high(pRoot.right); if (Math.abs(left - right) > 1) { return false; } if (!IsBalanced_Solution(pRoot.left)) { return false; } return IsBalanced_Solution(pRoot.right); } private int high(TreeNode pRoot) { if (pRoot == null) { return 0; } return Math.max(high(pRoot.left) + 1, high(pRoot.right) + 1); } }