import java.util.*; /* * public class TreeNode { * int val = 0; * TreeNode left = null; * TreeNode right = null; * } */ public class Solution { /** * * @param root TreeNode类 树的根节点 * @return bool布尔型 */ public boolean isBalanced (TreeNode root) { // write code here if(root == null) return true; // 空树也是平衡数 else // 否则计算左右子树的高度差是否<=1 return Math.abs(treeDepth(root.left) - treeDepth(root.right)) <= 1; } private int treeDepth(TreeNode root) { if(root == null) return 0; int left = treeDepth(root.left); int right = treeDepth(root.right); return Math.max(left, right) + 1; } }