题解 | #判断是不是平衡二叉树#
判断是不是平衡二叉树
https://www.nowcoder.com/practice/8b3b95850edb4115918ecebdf1b4d222
import java.util.*;
/*
* public class TreeNode {
* int val = 0;
* TreeNode left = null;
* TreeNode right = null;
* public TreeNode(int val) {
* this.val = val;
* }
* }
*/
public class Solution {
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param pRoot TreeNode类
* @return bool布尔型
*/
public boolean IsBalanced_Solution (TreeNode pRoot) {
// write code here
if(pRoot==null){
return true;
}
int res = IsBalanced_Solution1(pRoot);
return res>=0;
}
public int IsBalanced_Solution1 (TreeNode pRoot) {
// write code here
if(pRoot==null){
return 0;
}
int a = IsBalanced_Solution1(pRoot.left);
int b = IsBalanced_Solution1(pRoot.right);
if(a>=0 && b>=0 && Math.abs(a-b)<=1){
return Math.max(a,b)+1;
}else{
return -1;
}
}
}
查看23道真题和解析

安克创新 Anker公司福利 699人发布