判断二叉树是否平衡(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

你可能感兴趣的:(二叉树)