思路
code
public boolean isBalanced(TreeNode root) {//判断树的深度是否为-1 -1表示不平衡return depth(root)!=-1;}//递归求树的深度 这里用-1表示树不平衡 否则表示树的深度public int depth(TreeNode root){if(root==null) //如果到达了最后一层 返回深度为0return 0;int leftDep = depth(root.left); //递归计算左右子树深度int rightDep = depth(root.right);if(leftDep==-1||rightDep==-1) //有一个不平衡则返回不平衡return -1;//判断差值 如果<2说明平衡 返回深度 否则返回-1return Math.abs(leftDep-rightDep)<2?Math.max(leftDep,rightDep)+1:-1;}
