判断一棵树是否平衡二叉树

【题目】判断一棵树是否为平衡二叉树
所谓平衡二叉树,是指一 棵空树或它的左右两个子树的高度差的绝对值不超过1,并且左右两个子树都是一棵平衡二叉树。

/**
 * @description
 */
public class CheckIsBanlanceBinaryTree {

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

        public TreeNode(int data) {
            this.value = data;
        }
    }

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

    //返回值为 -1 表示 root 不是平衡树
    private int getDepth(TreeNode root) {
        if (root == null) {
            return 0;
        }
        int left = getDepth(root.left);
        if (left == -1) {
            return -1;
        }
        int right = getDepth(root.right);
        if (right == -1) {
            return -1;
        }
        //如果非平衡,直接返回-1,否则返回当前子树最大深度给上一层递归计算高度差
        return Math.abs(left - right) > 1 ? -1 : 1 + Math.max(left, right);
    }
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容