版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/sqh201030412/article/details/78679779
Given a binary tree, determine if it is height-balanced.
For this problem, a height-balanced binary tree is defined as a binary tree in which the depth of the two subtrees of every node never differ by more than 1.
给定一棵二叉树,确定它是否是高度平衡的。
对于这个问题,一个高度平衡二叉树定义为一个二叉树,其深度两子树节点不会相差超过1
//递归 深度优先 维护深度
public boolean isBalanced(TreeNode root) {
return isBalancedHelp(root) >=0;
}
public int isBalancedHelp(TreeNode root){
if(root ==null){ //递归正常结束条件
return 0;
}
int left = isBalancedHelp(root.left);//深度
int right = isBalancedHelp(root.right);//同层 right
if(left < 0 || right <0){ //不平衡提前结束条件
return -1;
}
if(Math.abs(left - right)>1){//判断是否不平衡
return -1;
}
return Math.max(left, right)+1;//维护到当前节点最大深度
}