题目:平衡二叉树
题目描述
输入一棵二叉树,判断该二叉树是否是平衡二叉树。
思路
平衡二叉树:它是一棵空树或它的左右两个子树的高度差的绝对值不超过1,并且左右两个子树都是一棵平衡二叉树。
于是就有了以下代码:
class Solution {
public:
bool IsBalanced_Solution(TreeNode* pRoot) {
if(!pRoot) return true;
//左右子树深度小于1,并且左右子树也是平衡二叉
return (
abs(GetDepth(pRoot->left)-GetDepth(pRoot->right))<=1 &&
IsBalanced_Solution(pRoot->left) && IsBalanced_Solution(pRoot->right)
);
}
private:
//获取当前子树的深度
int GetDepth(TreeNode *r){
if(!r) return 0;
int left = GetDepth(r->left)+1;
int right = GetDepth(r->right)+1;
return max(left, right);
}
};
当仔细思考,会出现重复遍历的情况,于是修改代码,只要左右子树不是平衡二叉树就返回-1
class Solution {
public:
bool IsBalanced_Solution(TreeNode* pRoot) {
return GetDepth(pRoot)!=-1;
}
private:
//获取当前子树的深度
int GetDepth(TreeNode *r){
if(!r) return 0;
int left = GetDepth(r->left)+1;
if(left==0) return -1;
int right = GetDepth(r->right)+1;
if(right==0) return -1;
return abs(left-right)<=1 ? max(left, right):-1;
}
};