问题:输入一棵二叉树,判断该二叉树是不是平衡二叉树。spa
先求出左右两个子树的深度,若他们的深度差的绝对值>1,则不是平衡二叉树,还有一点最重要的是性质中说了左右两个子树都是一棵平衡二叉树,因此还要判断code
IsBalanced_Solution(root.left)&&IsBalanced_Solution(root.right) public class Solution { public boolean IsBalanced_Solution(TreeNode root) { if(root==null){ return true; } if(Math.abs(TreeDepath(root.left)-TreeDepath(root.right))>1) return false; return IsBalanced_Solution(root.left)&&IsBalanced_Solution(root.right); } //求二叉树的深度 public int TreeDepath(TreeNode pRoot){ if(pRoot==null) return 0; if(TreeDepath(pRoot.left)>=TreeDepath(pRoot.right)){ return 1+TreeDepath(pRoot.left); }else{ return 1+TreeDepath(pRoot.right); } } }