guanpengchn / guanpengchn.github.io

:memo: code on DEV branch, blogs on ISSUES
https://guanpengchn.github.io
18 stars 9 forks source link

平衡二叉树 #48

Open guanpengchn opened 5 years ago

guanpengchn commented 5 years ago

题目描述

输入一棵二叉树,判断该二叉树是否是平衡二叉树。

class Solution {
public:
    int Calc(TreeNode* pRoot){
        if(pRoot == nullptr){
            return 0;
        }
        int left = Calc(pRoot->left);
        if(left == -1){
            return -1;
        }
        int right = Calc(pRoot->right);
        if(right == -1){
            return -1;
        }
        return abs(right - left)>1?-1:max(right,left)+1;
    }
    bool IsBalanced_Solution(TreeNode* pRoot) {
        if(Calc(pRoot) == -1){
            return false;
        }
        return true;
    }
};