利用两个递归函数,第一个递归函数是用来求当前结点的左右子树的高度;第二个递归函数是用来判断当前节点的左右子树是不是平衡二叉树。
import java.util.*;
/*
* public class TreeNode {
* int val = 0;
* TreeNode left = null;
* TreeNode right = null;
* }
*/
public class Solution {
/**
*
* @param root TreeNode类
* @return bool布尔型
*/
public boolean isBalanced (TreeNode root) {
// write code here
if(root==null)
return true;
if(Math.abs(isB(root.left)-isB(root.right)) > 1)
return false;
return isBalanced(root.left)&&isBalanced(root.right);
}
public int isB(TreeNode root){
if(root==null)
return 0;
int l = isB(root.left);
int r = isB(root.right);
return Math.max(l,r) + 1;
}
}
京公网安备 11010502036488号