题目描述
输入一棵二叉树,判断该二叉树是否是平衡二叉树。
方法一:
在判断左右子树是否为平衡二叉树的同时也在计算当前子树的深度depth;
之后返回根节点后,如果左右子树深度之差大于1,则返回false,否则返回左右子树的判断结果。
class Solution {
bool JudgeBalance(TreeNode* pRoot, int &depth) {
if (!pRoot)
return true;
int leftDepth = 0;
int rightDepth = 0;
bool leftJudge = JudgeBalance(pRoot->left, leftDepth);
bool rightJudge = JudgeBalance(pRoot->right, rightDepth);
depth = (leftDepth > rightDepth ? leftDepth : rightDepth) + 1;
if (abs(leftDepth - rightDepth) <= 1)
return leftJudge && rightJudge;
else
return false;
}
public:
bool IsBalanced_Solution(TreeNode* pRoot) {
int depth = 0;
return JudgeBalance(pRoot, depth);
}
};
方法二:
从下往上遍历,如果子树是平衡二叉树,则返回子树的高度;如果发现子树不是平衡二叉树,则直接停止遍历,这样至多只对每个结点访问一次。
class Solution {
int GetDepth(TreeNode* pRoot) {
if (!pRoot)
return true;
int leftDepth = GetDepth(pRoot->left);
if (leftDepth == -1)
return -1;
int rightDepth = GetDepth(pRoot->right);
if (rightDepth == -1)
return -1;
return abs(leftDepth-rightDepth) > 1 ? -1 : 1 + max(leftDepth, rightDepth);
}
public:
bool IsBalanced_Solution(TreeNode* pRoot) {
return GetDepth(pRoot) != -1;
}
};