剑指offer--平衡二叉树

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/weixin_40921797/article/details/82112702

输入一棵二叉树,判断该二叉树是否是平衡二叉树。
思路:首先什么是平衡二叉树,左子树和右子树深度之差小于等于1,则为平衡而叉树,为什么是<=1因为有奇数个节点,和有偶数个节点不一样。我们从根开始不断的访问他的左右子树,不断的求左右子树的深度,如果深度之差<=1则是平衡二叉树返回真,否则为假。

class Solution {
public:
    int TreeDepth(TreeNode *pRoot)
    {
        if(pRoot ==NULL)
            return 0;
        else
        {
            int nl= TreeDepth(pRoot->left);
            int nr = TreeDepth(pRoot->right);
            return (nl > nr) ? (nl + 1) : (nr + 1);
        }
    }
    bool IsBalanced_Solution(TreeNode* pRoot) {
        if (pRoot == NULL)
            return true;
        else 
        {
            int l = TreeDepth(pRoot->left);
            int r = TreeDepth(pRoot->right);
            if(l - r< 2&& l - r> -2)
            {
                if(IsBalanced_Solution(pRoot->left) == false
                   ||IsBalanced_Solution(pRoot->right) == false)
                    return false;
                else return true;
            }
            else return false;
        }
        }
};

猜你喜欢

转载自blog.csdn.net/weixin_40921797/article/details/82112702