問題:輸入一棵二叉樹,判斷該二叉樹是不是平衡二叉樹。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); } } }