初次拿到这道题,也是一点思路没有,但是根据之前求最深的函数就可以得知了
public static boolean isBalanced(TreeNode root) {
if(root == null){
return true;
}else {
Queue<TreeNode> mid = new LinkedList<>();
mid.offer(root);
while(!mid.isEmpty()){
root = mid.poll();
int left = 0;
int right = 0;
if(root.left != null){
left = maxDepth2(root.left);
mid.offer(root.left);
}
if(root.right != null){
right = maxDepth2(root.right);
mid.offer(root.right);
}
int i = Math.max(left, right);
int j = Math.min(left, right);
System.out.println("i的值 "+i);
System.out.println("j的值 "+j);
if(i - j> 1){
return false;
}
}
return true;
}
}
看一下排名比较高的代码,有点懵逼
class Solution {
public boolean isBalanced(TreeNode root) {
if(height(root)>-1){
return true;
} else {
return false;
}
}
public boolean bb(int h_lf,int h_ri)
{
return h_lf-h_ri>0?h_lf-h_ri<=1:h_ri-h_lf<=1;
}
public int height(TreeNode t) {
if(t == null) {
return 0;
}
int left = height(t.left);
if(left == -1) {
return -1;
}
int right = height(t.right);
if(right == -1) {
return -1;
}
if(!bb(left,right)){
return -1;
}
return max(left,right)+1;
}
public int max(int a,int b){
return a>b?a:b;
}
}
再看一个排名较高的代码:充分使用递归来解这道题目,首先看到的是先判断根节点左右两个的深度,之后用递归来分别对左右两个进行递归返回,使用的同样是取出深度进行比较,但是这里没有使用将每个节点都取出来保存,而是直接使用递归来进行判断读取
public boolean isBalanced(TreeNode root) {
if(root==null){
return true;
}
int leftL=getHeight(root.left);
int rightL=getHeight(root.right);
if(Math.abs(leftL-rightL)<=1){
return isBalanced(root.left)&&isBalanced(root.right);
}
return false;
}
public int getHeight(TreeNode root){
if(root==null){
return 0;
}
int leftL=getHeight(root.left);
int rightL=getHeight(root.right);
return leftL>rightL?leftL+1:rightL+1;
}