39.平衡二叉树——剑指offer

 

class Solution {
public:
    bool IsBalanced_Solution(TreeNode* pRoot) {
        if(pRoot==NULL) return true;
        int left = getDepth(pRoot->left);  //pRoot是跟节点.
        int right = getDepth(pRoot->right);
        int dif = left - right;
          
        if(dif < -1 || dif > 1)
            return false;
        else
            return IsBalanced_Solution(pRoot->left) && IsBalanced_Solution(pRoot->right);    //递归(循环).
    }
      
    int getDepth(TreeNode *root){
        if(!root) return 0;
          
        int left = getDepth(root->left);
        int right = getDepth(root->right);
          
        return left > right ? left + 1 : right + 1;
    }
};
class Solution {
public:
    bool IsBalanced_Solution(TreeNode* pRoot) {
        if(helper(pRoot) < 0) return false;
        return true;
    }
private:
    int helper(TreeNode* node){
        if(node == NULL) return 0;
        int ld = helper(node->left);
        if(ld == -1) return -1;    //若左边已经不是平衡二叉树了,那就直接返回,没必要搜索右边了
        int rd = helper(node->right);    
        if(rd == -1 || abs(ld-rd) > 1) return -1; //-1代表:不是平衡二叉树
        return max(ld, rd)+1;
    }
};

 

posted @ 2019-06-04 18:17  unique_ptr  阅读(90)  评论(0编辑  收藏  举报