判断二叉树是否为平衡二叉树

#include "Tree.h"
using namespace std;
int getHeight(Node* head, int level, bool* res)
{
    if(head == nullptr)
        return level;
    int Lh = getHeight(head->left, level + 1, res);
    if(!*res)
        return level;
    int Rh = getHeight(head->right, level + 1, res);
    if(!*res)
        return level;
    if(abs(Lh - Rh) > 1)
        *res = false;
    return max(Lh, Rh);
}
bool isBalance(Node* head)
{
    bool res = true;
    getHeight(head, 1, &res);
    return res;
}
int main()
{
     Node* pNode0 = new Node(5);
    Node* pNode1 = new Node(7);
    Node* pNode2 = new Node(3);
    Node* pNode3 = new Node(4);
    Node* pNode4 = new Node(5);
    Node* pNode5 = new Node(6);
    Node* pNode6 = new Node(8);

    connectTree(pNode0, pNode1, pNode2);
    connectTree(pNode1, pNode3, pNode4);
    connectTree(pNode2, pNode5, pNode6);

    cout << isBalance(pNode0) << endl;
}

猜你喜欢

转载自blog.csdn.net/wzc2608/article/details/80869804