【剑指offer】判断二叉树是否平衡(左右子树高度差最多为1)

class Solution {
public:
    bool IsBalanced_Solution(TreeNode* pRoot) {
		int depth = -1;
        return IsBalanced(pRoot,&depth);
    }
    bool IsBalanced(TreeNode* pRoot,int *depth){
        if(pRoot == NULL){
            *depth = 0;
            return true;
        }
        int left = -1;
        int right = -1;
        if(IsBalanced(pRoot->left,&left) && IsBalanced(pRoot->right,&right)){
            int diff = left - right;
            if(diff <= 1 && diff >= -1){
                *depth = 1 + (left > right ? left : right);
                return true;
            }
        }
        return false;
    }
};

没有专门利用  TreeDepth 函数 来递归计算二叉树的深度,而是在计算二叉树深度的同时来判断是否平衡。

    原文作者:平衡二叉树
    原文地址: https://blog.csdn.net/CSDNJACK_/article/details/48441391
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞