/**
* 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);
}
}
}
LeetCode110:Balanced Binary Tree
最新推荐文章于 2018-04-26 21:59:50 发布