[剑指offer] 39. 平衡二叉树

题目描述

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

思路:
比较左右深度,如果差值大于1,则不平衡。
利用后序遍历,避免每次都从头遍历一次。
遍历过程中,当左节点出现不平衡时,也不需要遍历右节点了,剪枝
class Solution
{
  public:
    int getDepth(TreeNode *pRoot)
    {
        if (pRoot == NULL)
            return 0;
        int left = getDepth(pRoot->left);
        if (left == -1)
            return -1;
        int right = getDepth(pRoot->right);
        if (right == -1)
            return -1;
        if (left - right > 1 || left - right < -1)
            return -1;
        else
            return max(left, right) + 1;
    }
    bool IsBalanced_Solution(TreeNode *pRoot)
    {
        return getDepth(pRoot) != -1;
    }
};

 

posted @ 2018-12-20 10:27  Ruohua3kou  阅读(115)  评论(0编辑  收藏  举报