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

版权声明:转载请备注原文链接 https://blog.csdn.net/qq_40868987/article/details/82896257

Question:输入一棵二叉树,判断该二叉树是否是平衡二叉树。

解:首先判断树根是否为空,如果为空,则即为平衡二叉树,如不为空,则判断该根节点的左子树与右子树的高度差的绝对值是否大于1,如为真,则该二叉树不是平衡二叉树,否则递归遍历每个结点的左、右子树,若所有结点的左右子树的高度差的绝对值都不大于1,则该树即为平衡而二叉树

public class Solution {
   public boolean IsBalanced_Solution(TreeNode root) {
        if (root == null)
            return true;
 
        if (Math.abs(getHeight(root.left) - getHeight(root.right)) > 1)
            return false;
        return IsBalanced_Solution(root.left) && IsBalanced_Solution(root.right);
        //此处if语句代码也可写成下面一行代码,但可读性不太好
 //return Math.abs(maxDepth(root.left) - maxDepth(root.right)) <= 1 &&IsBalanced_Solution(root.left) && IsBalanced_Solution(root.right);
    }
 
    public int getHeight(TreeNode root) {
        if (root == null)
            return 0;
int lDepth=getHeight(root.left);
           int rDepth=getHeight(root.right);
           return (lDepth > rDepth ? lDepth : rDepth) + 1;

/*   或者通过max比较来返回
return max(getHeight(root.left), getHeight(root.right)) + 1;
    }
 
    private int max(int a, int b) {
        return (a > b) ? a : b;
*/
    }
}

分析以上代码,由于判断上层结点的时,下层结点会被重复遍历,从时间效率以及开销考虑,还可以再优化,改为从下往上遍历,判断结点的子树是否平衡,若平衡才返回树的深度,否则停止遍历。

public class Solution {
    public boolean IsBalanced_Solution(TreeNode root) {
        if (root == null) {
            return true;
        }
        int left = getTreeDepth(root.left);
        int right = getTreeDepth(root.right);
        int diff = left - right;
        if (diff > 1 || diff < -1)
            return false;
        return IsBalanced_Solution(root.left) && IsBalanced_Solution(root.right);
         
    }
     
     
    public  int getTreeDepth(TreeNode root) {
        if (root == null)
            return 0;
        else
            return Math.max(getTreeDepth(root.left), getTreeDepth(root.right)) + 1;
 
    }
}

补充:

平衡二叉搜索树(Self-balancing binary search tree)又被称为AVL树(有别于AVL算法),且具有以下性质:它是一 棵空树或它的左右两个子树的高度差的绝对值不超过1,并且左右两个子树都是一棵平衡二叉树。平衡二叉树的常用实现方法有红黑树AVL替罪羊树Treap伸展树等。 最小二叉平衡树的节点总数的公式如下 F(n)=F(n-1)+F(n-2)+1 这个类似于一个递归的数列,可以参考Fibonacci(斐波那契)数列,1是根节点,F(n-1)是左子树的节点数量,F(n-2)是右子树的节点数量。

猜你喜欢

转载自blog.csdn.net/qq_40868987/article/details/82896257