package JianZhioffer; /** * 输入一棵二叉树的根节点,判断该树是不是平衡二叉树。如果某二叉树中任意节点的左右子树的深度相差不超过1,那么它就是一棵平衡二叉树。 */ //思路:1.左子树平衡 // 2.右子树平衡 // 3.左右差别最大1 public class test55II { public static void main(String[] args) { TreeNode t=new TreeNode(3); t.left=new TreeNode(9); t.right=new TreeNode(20); t.right.left=new TreeNode(15); t.right.right=new TreeNode(7); System.out.println(isBalanced(t)); } public static boolean isBalanced(TreeNode root) { if(root==null){ return true; } if(!isBalanced(root.left)){ return false; } if(!isBalanced(root.right)){ return false; } int l=helper(root.left); int r=helper(root.right); if(Math.abs(l-r)>1){ return false; }else{ return true; } } public static int helper(TreeNode root){ if(root==null){ return 0; } int left=helper(root.left)+1; int right=helper(root.right)+1; return Math.max(left, right); } }