剑指 Offer 55 - II. 平衡二叉树

  1. /**
  2. * Definition for a binary tree node.
  3. * public class TreeNode {
  4. * int val;
  5. * TreeNode left;
  6. * TreeNode right;
  7. * TreeNode(int x) { val = x; }
  8. * }
  9. */
  10. class Solution {
  11. public boolean isBalanced(TreeNode root) {
  12. if (root == null)
  13. return true;
  14. return Math.abs(height(root.left) - height(root.right)) <= 1 && isBalanced(root.left) && isBalanced(root.right);
  15. }
  16. private int height(TreeNode root) {
  17. if (root == null)
  18. return 0;
  19. return Math.max(height(root.left), height(root.right)) + 1;
  20. }
  21. }