image.png

解题思路

image.png

  1. class Solution {
  2. public boolean isBalanced(TreeNode root) {
  3. return depth(root)!=-1;
  4. }
  5. public int depth(TreeNode root){
  6. if(root==null) return 0;
  7. int left = depth(root.left);
  8. if(left==-1) return -1;
  9. int right = depth(root.right);
  10. if(right==-1) return -1;
  11. return Math.abs(left-right)<2?Math.max(left,right)+1:-1;
  12. }
  13. }