package org.example.test;

public class IsBalancedTest {

    static public class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;

        public TreeNode(int val) {
            this.val = val;
        }
    }

    public boolean IsBalanced_Solution(TreeNode root) {
        return getHight(root) != -1;
    }

    /**
     * 练习一段时间后,发现这些以前做不来的,现在轻松就做出来了。
     * 加油,多练习!
     *
     * @param root
     * @return
     */
    private int getHight(TreeNode root) {
        if (root == null) {
            return 0;
        }
        int z = 0;
        int x = getHight(root.left);
        if (x == -1) {
            return -1;
        }
        int y = getHight(root.right);
        if (y == -1) {
            return -1;
        }
        if (Math.abs(y - x) > 1) {
            return -1;
        } else {
            z = Math.max(x, y) + 1;
        }
        return z;
    }
}