前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >剑指Offer-平衡二叉树

剑指Offer-平衡二叉树

作者头像
武培轩
发布2018-04-18 17:02:02
6990
发布2018-04-18 17:02:02
举报
文章被收录于专栏:武培轩的专栏武培轩的专栏
代码语言:javascript
复制
package Tree;

/**
 * 平衡二叉树
 * 输入一棵二叉树,判断该二叉树是否是平衡二叉树。
 * 平衡二叉树(Balanced Binary Tree)又被称为AVL树(有别于AVL算法),且具有以下性质:
 * 它是一棵空树或它的左右两个子树的高度差的绝对值不超过1,并且左右两个子树都是一棵平衡二叉树。
 */
public class Solution20 {
    public static void main(String[] args) {
        Solution20 solution20 = new Solution20();
        int[] array = {8, 6, 10, 5, 7, 9, 11};
        TreeNode treeNode = solution20.createBinaryTreeByArray(array, 0);
        System.out.println(solution20.IsBalanced_Solution_2(treeNode));
    }

    /**
     * 从下往上遍历,如果子树是平衡二叉树,则返回子树高度,否则返回-1
     * 时间复杂度:O(n)
     *
     * @param root
     * @return
     */
    public boolean IsBalanced_Solution_2(TreeNode root) {
        return MaxDepth_2(root) != -1;
    }

    public int MaxDepth_2(TreeNode root) {
        if (root == null) {
            return 0;
        }
        int leftHeight = MaxDepth_2(root.left);
        if (leftHeight == -1) {
            return -1;
        }
        int rightHeight = MaxDepth_2(root.right);
        if (rightHeight == -1) {
            return -1;
        }
        return Math.abs(leftHeight - rightHeight) > 1 ? -1 : 1 + Math.max(leftHeight, rightHeight);
    }

    /**
     * 遍历每个结点,借助一个获取树深度的递归函数,根据该结点的左右子树高度差判断是否平衡,然后递归地对左右子树进行判断。
     * 时间复杂度:O(n^2)
     *
     * @param root
     * @return
     */
    public boolean IsBalanced_Solution(TreeNode root) {
        if (root == null) {
            return true;
        }
        if (Math.abs(MaxDepth(root.left) - MaxDepth(root.right)) > 1)
            return false;
        return IsBalanced_Solution(root.left) && IsBalanced_Solution(root.right);
    }

    public int MaxDepth(TreeNode root) {
        if (root == null) {
            return 0;
        }
        return 1 + Math.max(MaxDepth(root.left), MaxDepth(root.right));
    }

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

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

        }

    }

    public TreeNode createBinaryTreeByArray(int[] array, int index) {
        TreeNode tn = null;
        if (index < array.length) {
            int value = array[index];
            tn = new TreeNode(value);
            tn.left = createBinaryTreeByArray(array, 2 * index + 1);
            tn.right = createBinaryTreeByArray(array, 2 * index + 2);
            return tn;
        }
        return tn;
    }

}
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2018-03-22 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档