39. Balanced Binary Tree

Topic description

         Input a binary tree to determine whether the binary tree is a balanced binary tree.

Problem solving ideas

         The height difference between the left and right subtrees of a balanced binary tree is at most 1;

    private class TreeNode {
        int val = 0;
        TreeNode left = null;
        TreeNode right = null;

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

        }
    }

    private int getTreeDepth(TreeNode root) {
        if (root == null) {
            return 0;
        }

        int left = getTreeDepth(root.left);
        if (left == -1) {
            return -1;
        }
        int right = getTreeDepth(root.right);
        if (right == -1) {
            return -1;
        }

        return Math.abs(left - right) > 1 ? -1 : 1 + Math.max(getTreeDepth(root.left), getTreeDepth(root.right));
    }

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

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325868288&siteId=291194637