牛客网-剑指office-平衡二叉树

题目:输入一棵二叉树,判断该二叉树是否是平衡二叉树。
解法一:
思路:利用上道题二叉树的深度的函数,每次比较左右节点的深度即可。但是这种方法需要重复遍历节点多次,使得时间效率不高。

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

解法二:
思路:如果子树不是平衡二叉树,直接返回深度为-1

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

你可能感兴趣的:(牛客网-剑指office-平衡二叉树)