您的位置:首页 > 其它

LeetCode110:Balanced Binary Tree

2016-12-11 11:15 337 查看


/**
* Definition for a binary tree node.
* public class TreeNode {
*     int val;
*     TreeNode left;
*     TreeNode right;
*     TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public int getDepth(TreeNode root, int curDepth){
////如果为空 则返回当前的深度
if(root==null) return curDepth;
//返回子树中最大的深度
return Math.max(getDepth(root.left,curDepth+1),getDepth(root.right,curDepth+1));

}
public boolean isBalanced(TreeNode root) {
//树为空
if(root==null) return true;
//左子树的最大深度
int left = getDepth(root.left,1);
//右子树的最大深度
int right = getDepth(root.right,1);
//深度之差不能大于1 否则不平衡
if(Math.abs(left-right)>1){
return false;
}else{
//左子树和右子树是否为平衡树
return isBalanced(root.left) && isBalanced(root.right);
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息