/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/classSolution{
int right =0;
int left =0;public boolean isBalanced(TreeNode root){if(root ==null||(root.right==null&&root.left==null)){returntrue;}elseif(Math.abs(right-left)>1){returnfalse;}else{
right++;
left++;isBalanced(root.left);isBalanced(root.right);}returntrue;}}
正确的
classSolution{public boolean isBalanced(TreeNode root){if(root==null)returntrue;if(Math.abs(Depth(root.left)-Depth(root.right))>1)returnfalse;elsereturnisBalanced(root.left)&&isBalanced(root.right);}private int Depth(TreeNode root){//求深度if(root==null)return0;return Math.max(Depth(root.left),Depth(root.right))+1;}}