JZ39 --- 平衡二叉树

题目描述:
输入一棵二叉树,判断该二叉树是否是平衡二叉树。
在这里,我们只需要考虑其平衡性,不需要考虑其是不是排序二叉树。

题解:

平衡树(Balance Tree,BT) 指的是,任意节点的子树的高度差都小于等于1。
求出每颗子二叉树的子树高度差,如果大于1那就不是平衡二叉树,反之一定是。

	// 求子树高度差
    public int getDepth(TreeNode root){
        if(root == null){
            return 0;
        }
        int left = getDepth (root.left);
        int right = getDepth (root.right);
        return Math.max (left,right) + 1;
    }

    public boolean IsBalanced_Solution(TreeNode root) {
        if(root == null){
            return false;
        }
        if(!IsBalanced_Solution (root.left)){
            return false;
        }
        if(!IsBalanced_Solution (root.right)){
            return false;
        }

        int left = getDepth(root.left);
        int right = getDepth(root.right);
        int dif = left - right;
        if(Math.abs (dif) == 1){
            return false;
        }
        return false;
    }

你可能感兴趣的:(剑指offer)