Balanced Binary Tree --Leetcode C++

递归

  • 左子树是否为平衡二叉树
  • 右子树是否为平衡二叉树
  • 左右子树高度差是否大于1,大于1,返回false
  • 否则判断左右子树

 最简单的理解方法就是如下的思路:

class Solution {
public:
    bool isBalanced(TreeNode* root) {
        if(root==NULL){
            return true;
        }
        int ldepth=depth(root->left);
        int rdepth=depth(root->right);
        if(abs(ldepth-rdepth)>1)return false;
        else{
            return isBalanced(root->left)&&isBalanced(root->right);
        }
    }
    int depth(TreeNode *root){
        if(root==NULL){
            return 0;
        }
        int lleft=depth(root->left);
        int trigth=depth(root->right);
        return lleft>trigth ? lleft+1:trigth+1;

    }
};

在上面的方法中,每一个节点都会计算节点左子树和右子树的高度,存在大量的重复计算

所以,采用自底向上的方式

class Solution2 {
public:
    bool isBalanced(TreeNode* root) {
        if(root==NULL){
            return true;
        }
        int height=getheight(root);
        if(height==-1){
            return false;
        }
        return true;
    }
    int getheight(TreeNode *root){
        if(root==NULL){
            return 0;
        }
        int lleft=getheight(root->left);
        int trigth=getheight(root->right);
        if(lleft==-1||trigth==-1){
            return -1;
        }
        if(abs(lleft-trigth)>1){
            return -1;
        }
        return lleft>trigth? lleft+1:trigth+1;
    }
};

 

posted @ 2015-06-03 20:34  hitkb  阅读(130)  评论(0编辑  收藏  举报