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

2018年6月30日 26点热度 0条评论 来源: wzc2608
#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;
}
    原文作者:wzc2608
    原文地址: https://blog.csdn.net/wzc2608/article/details/80869804
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系管理员进行删除。