题目描述

判断给定的二叉树是否是平衡的
在这个问题中,定义平衡二叉树为每个节点的左右两个子树高度差的绝对值不超过1的二叉树

代码

  1. public static boolean isBalanced (TreeNode root) {
  2. if(root==null)
  3. return true;
  4. if(Math.abs(getDepth(root.left)-getDepth(root.right))>1) {
  5. return false;
  6. }
  7. return isBalanced(root.left)&&isBalanced(root.right);
  8. }
  9. public static int getDepth(TreeNode root) {
  10. if(root==null)
  11. return 0;
  12. int left = getDepth(root.left)+1;
  13. int right = getDepth(root.right)+1;
  14. return left>right?left:right;
  15. }