//判断一个树是不是平衡二叉树
//任何节点的左子树和右子树高度差不超过1
public class BalanceTree {
    public static void main(String[] args) {
        Node root = new Node(1);
        root.left = new Node(2);
        root.right = new Node(3);
        root.left.left = new Node(4);
        root.left.right = new Node(5);
        root.right.left = new Node(6);
        root.right.right = new Node(7);
        root.left.right.left = new Node(8);
        root.left.right.left.left = new Node(9);
        System.out.println(isB(root));
    }
    public static boolean isB(Node head) {
        return process(head).isB;
    }
    public static returnData process(Node head) {
        if (head == null) {
            return new returnData(true, 0);
        }
        returnData leftData = process(head.left);
        if (!leftData.isB) {
            return new returnData(false, 0);
        }
        returnData rightData = process(head.right);
        if (!rightData.isB) {
            return new returnData(false, 0);
        }
        if (Math.abs(leftData.h - rightData.h) > 1) {
            return new returnData(false, 0);
        }
        return new returnData(true, Math.max(leftData.h, rightData.h) + 1);
    }
    public static class returnData {
        boolean isB;
        int h;
        public returnData(boolean isB, int h) {
            this.isB = isB;
            this.h = h;
        }
    }
    public static class Node {
        Node left;
        Node right;
        int value;
        public Node(int value) {
            this.value = value;
        }
    }
}