判断二叉树是否平衡

二叉树平衡的定义:从根到任意一个叶子节点的距离相差不超过1。

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

struct Node{
    int value;
    Node *pLeft;
    Node *pRight;
};

int MaxDepth(Node *pRoot)
{
    if (!pRoot)
        return 0;

    return (MaxDepth(pRoot->pLeft) > MaxDepth(pRoot->pRight)) ? (MaxDepth(pRoot->pLeft + 1)) : (MaxDepth(pRoot->pRight) + 1);
}

int MinDepth(Node *pRoot)
{
    if (!pRoot)
        return 0;

    return MinDepth(pRoot->pLeft) < MinDepth(pRoot->pRight) ? (MinDepth(pRoot->pLeft + 1)) : (MinDepth(pRoot->pRight + 1));
}

bool IsBalanced(Node *pRoot)
{
    return (MaxDepth(pRoot) - MinDepth(pRoot) <= 1);
}

int main()
{
    
    return 0;
}

EOF

原文地址:https://www.cnblogs.com/lihaozy/p/2809917.html