剑指offer:判定平衡二叉树

平衡二叉树(Balanced Binary Tree)又被称为AVL树(有别于AVL算法),且具有以下性质:它是一 棵空树或它的左右两个子树的高度差的绝对值不超过1,并且左右两个子树都是一棵平衡二叉树。这个方案很好的解决了二叉查找树退化成链表的问题,把插入,查找,删除的时间复杂度最好情况和最坏情况都维持在O(logN)。但是频繁旋转会使插入和删除牺牲掉O(logN)左右的时间,不过相对二叉查找树来说,时间上稳定了很多。

题目描述:

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

总的想法: //判断根节点左右子树的深度,高度差超过1,则不平衡

方法一:

class Solution {
public:
    bool IsBalanced_Solution(TreeNode* pRoot,int &depth){
        if(pRoot==NULL){
            depth=0;
            return true;
        }
        int ld,rd;
        bool l=IsBalanced_Solution(pRoot->left,ld);
        bool r=IsBalanced_Solution(pRoot->right,rd);
        depth=1+max(ld,rd);
       if(l&&r&&(ld>rd?ld-rd:rd-ld)<=1)
            return true;
         
        else
            return false;
        
    }
             
    bool IsBalanced_Solution(TreeNode* pRoot) {
        int depth;
        return IsBalanced_Solution(pRoot,depth);
    }
};

方法二:(单独的函数求节点深度)




public class Solution {
    //判断根节点左右子树的深度,高度差超过1,则不平衡
    public boolean IsBalanced_Solution(TreeNode root) {
        if (root==null) {
            return true;
        }
        int left = getTreeDepth(root.left);
        int right = getTreeDepth(root.right);
        return (left-right)>1?false:true;
    }
    //求取节点的深度
    public static int getTreeDepth(TreeNode root) {
        if (root==null) {
            return 0;
        }
        int leftDepth = 1+getTreeDepth(root.left);
        int rightDepth = 1+getTreeDepth(root.right);
        return leftDepth>rightDepth?leftDepth:rightDepth;
    }
}


更多文章:http://my.csdn.net/wodeqingtian1234

猜你喜欢

转载自blog.csdn.net/wodeqingtian1234/article/details/72669947