题解 | #判断是不是平衡二叉树#
判断是不是平衡二叉树
https://www.nowcoder.com/practice/8b3b95850edb4115918ecebdf1b4d222
// 通过递归计算左右节点的深度判断是否为平衡二叉树
public class Solution {
public boolean IsBalanced_Solution(TreeNode root) {
if(computeDeep(root)<0){
return false;
}
return true;
}
int computeDeep(TreeNode root){
if(root==null){
return 0;
}
// 递归计算左右子数的深度
int left = computeDeep(root.left);
int right = computeDeep(root.right);
// 如果深度相差大于1,则返回负数值,向上返回都为负值
if(left-right>1 || left-right<-1){
return -2;
}
// 相差深度小于等于1,返回当前节点的深度
return Math.max(left,right)+1;
}
}


科大讯飞公司氛围 436人发布