二叉平衡树

题目描述:

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

基本知识:

平衡二叉搜索树(Self-balancing binary search tree)又被称为AVL树。

且具有以下性质:它是一 棵空树或它的左右两个子树的高度差的绝对值不超过1,并且左右两个子树都是一棵平衡二叉树。

 1 class Solution {
 2     int ldep = 0;
 3     int rdep = 0;
 4 public:
 5     int TreeDepth(TreeNode* pRoot){
 6         if(!pRoot) return 0 ;
 7             return max(1+TreeDepth(pRoot->left), 1+TreeDepth(pRoot->right));
 8     }
 9     bool IsBalanced_Solution(TreeNode* pRoot) {
10         if(!pRoot)
11             return true;
12         ldep = TreeDepth(pRoot->left);
13         rdep = TreeDepth(pRoot->right);
14         if(ldep - rdep > 1 || rdep - ldep > 1)
15             return false;
16         else
17         {
18             IsBalanced_Solution(pRoot->left);
19             IsBalanced_Solution(pRoot->right);
20         }
21         return true;
22     }
23 };

小黑的代码:

class Solution {
public:
    int IsBalance(TreeNode* pRoot) {
        if(pRoot == NULL) return 0;
        int ldep = IsBalance(pRoot -> left);
        int rdep = IsBalance(pRoot -> right);
        
        if(abs(ldep - rdep) <= 1 && ldep != -1 && rdep != -1) {
            return max(1 + ldep, 1 + rdep);
        }
        else return -1;
    }
    
    bool IsBalanced_Solution(TreeNode* pRoot) {
        if(IsBalance(pRoot) == -1) return false;
        else return true;
    }
};

 小黑的改进:

class Solution {
public:
    int IsBalance(TreeNode* pRoot) {
        if(pRoot == NULL) return 0;
        
        int ldep = IsBalance(pRoot -> left);
        if(ldep == -1) return -1;
        int rdep = IsBalance(pRoot -> right);
        if(rdep == -1) return -1;
        
        if(abs(ldep - rdep) <= 1 ) {
            return max(1 + ldep, 1 + rdep);
        }
        else return -1;
    }
    
    bool IsBalanced_Solution(TreeNode* pRoot) {
        if(IsBalance(pRoot) == -1) return false;
        else return true;
    }
};

 

posted @ 2018-04-10 16:25  Lune-Qiu  阅读(135)  评论(0编辑  收藏  举报