public static class Node { public int value; public Node left; public Node right;
public Node(int data) { this.value = data; } }
public static boolean isBalance(Node head) { boolean[] res = new boolean[1]; res[0] = true; int h = getHeight(head, 1, res); System.out.println(h); return res[0]; }
public static int getHeight(Node head, int level, boolean[] res) { if (head == null) { return level; } //递归求出左子树的高度 int lH = getHeight(head.left, level + 1, res); if (!res[0]) { return level; } //递归求出右子树的高度 int rH = getHeight(head.right, level + 1, res); if (!res[0]) { return level; } //如果左子树和右子树的高度差大于1,则认为这棵树不是平衡的 if (Math.abs(lH - rH) > 1) { res[0] = false; } //也可以返回树的高度 return Math.max(lH, rH); }