Java
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public boolean isBalanced(TreeNode root) {
if(root==null) return true;
if(isTmp(root)<0) return false;
return true;
}
public int isTmp(TreeNode root) {
if(root==null) return 0;
else
{
if(root.left!=null)
root.left.val=isTmp(root.left)+1;
if(root.right!=null)
root.right.val=isTmp(root.right)+1;
if(root.left!=null&&root.right!=null)
{
if(root.left.val-root.right.val>1||root.left.val-root.right.val<-1)
return -1000;
root.val=root.left.val>root.right.val?root.left.val:root.right.val;
}
else if(root.left==null&&root.right!=null)
{
if(root.right.val>1)
return -1000;
root.val=root.right.val;
}
else if(root.right==null&&root.left!=null)
{
if(root.left.val>1)
return -1000;
root.val=root.left.val;
}
else
root.val=0;
}
return root.val;
}
}
优解,Java,利用height来进行判断,比我写的简练
public boolean isBalanced(TreeNode root) {
if(root==null){
return true;
}
return height(root)!=-1;
}
public int height(TreeNode node){
if(node==null){
return 0;
}
int lH=height(node.left);
if(lH==-1){
return -1;
}
int rH=height(node.right);
if(rH==-1){
return -1;
}
if(lH-rH<-1 || lH-rH>1){
return -1;
}
return Math.max(lH,rH)+1;
}
网友评论