判断二叉树是否平衡(Bottom-up)

 

#include <iostream>
#include <vector>
using namespace std;

struct BTreeNode{
    int value;
    BTreeNode *lchild;
    BTreeNode *rchild;
};

bool IsBalanced(BTreeNode *pRoot, int &height){
    if (!pRoot){
        height = 0;
        return true;
    }

    int leftHeight = 0;
    int rightHeight = 0;
    bool leftBalance = false;
    bool rightBalance = false;

    leftBalance = IsBalanced(pRoot->lchild, leftHeight);
    rightBalance = IsBalanced(pRoot->lchild, rightHeight);

    if (leftBalance && rightBalance && abs(leftHeight - rightHeight) <= 1){
        height = leftHeight > rightHeight ? leftHeight + 1 : rightHeight + 1;
        return true;
    }
    else
        return false;
}

bool IsBalanced(BTreeNode *pRoot){
    if (!pRoot)
        return false;

    int height = 0;
    return IsBalanced(pRoot, height);
}


int main()
{

    return 0;
}

 

 

 

 

 

EOF

posted on 2012-12-17 14:11  kkmm  阅读(349)  评论(0编辑  收藏  举报