[剑指Offer]判断一棵树为平衡二叉树(递归)

题目链接

https://www.nowcoder.com/practice/8b3b95850edb4115918ecebdf1b4d222?tpId=0&tqId=0&rp=2&ru=/ta/coding-interviews&qru=/ta/coding-interviews/question-ranking

题意

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

思路

法一,定义版:按定义,自上而下遍历树,会有重复计算。
法二,优化版:自下而上遍历树,若不平衡则返回-1,至多遍历树一遍。

相关知识

平衡二叉树:或空树,或根结点左右子树高度差<=1,且左右子树也为平衡二叉树。

代码

定义版

class Solution {
public:
    bool IsBalanced_Solution(TreeNode* pRoot) {
        if(pRoot==NULL){return true;}
        else if(abs(getDepth(pRoot->left)-getDepth(pRoot->right))<=1){
            return true;
        }
        return false;
    }
private:
    int getDepth(TreeNode* pRoot){
        if(pRoot==NULL){return true;}
        else return max(getDepth(pRoot->left),getDepth(pRoot->right))+1;
    }
};

优化版

class Solution {
public:
    bool IsBalanced_Solution(TreeNode* pRoot) {
        return getDepth(pRoot)!=-1;
    }
private:
    int getDepth(TreeNode* pRoot){
        if(pRoot==NULL){return 0;}
        else{
            int left=getDepth(pRoot->left);
            if(left==-1){return -1;}
            
            int right=getDepth(pRoot->right);
            if(right==-1){return -1;}
            
            if(abs(right-left)>1){return -1;}
            else{return max(left,right)+1;}
        }
    }
};
原文地址:https://www.cnblogs.com/coding-gaga/p/10417603.html