题目链接这里
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
private boolean balanced=true;
public boolean isBalanced(TreeNode root) {
real(root);
return balanced;
}
public int real(TreeNode root)
{
if(!balanced)
{
return -1;
}
if(root==null)
{
return 0;
}
int leftDeep=real(root.left);
int rightDeep=real(root.right);
if(Math.abs(leftDeep-rightDeep)>1)
{
balanced=false;
return -1;
}
else
{
return Math.max(leftDeep,rightDeep)+1;
}
}
}