时间限制:1秒 空间限制:32768K 热度指数:253889
本题知识点: 树
题目描述
输入一棵二叉树,判断该二叉树是否是平衡二叉树。
题目链接:题目链接
这题想错了,我的想法是:
维护一个maxn为最大层数,
同时维护当前节点的深度depth,
当遍历到根节点时判断depth和maxn差值是否为1。
但是,这个思路会被hack掉。
比如[1,2,3,4,5,#,6,#,#,7]
当遍历到3的左节点的时候,为空节点,此时depth为2,而记录的maxn为4,差值为2.但是这是一个平衡树。
//WA的代码 class Solution { public: int maxn = 0; bool IsBalanced_Solution(TreeNode* pRoot) { maxn = 0; return isBalanced(pRoot, 0); } bool isBalanced(TreeNode* pRoot, int depth){ if (pRoot == NULL){ if(abs(depth-maxn) > 1) return false; return true; } depth ++ ; if(depth > maxn){ maxn = depth; } return isBalanced(pRoot->left,depth) && isBalanced(pRoot->right,depth); } };
这时,回到平衡树的定义,对于根节点,左右子树的最大深度值相差不超过1。所以应该维护左右子树的最大深度,然后判断是否差值不超过1。
class Solution {
public:
bool IsBalanced_Solution(TreeNode* pRoot) {
if(pRoot == NULL){
return true;
}
return abs(getDepth(pRoot->left) - getDepth(pRoot->right)) <= 1 ?
IsBalanced_Solution(pRoot->left) && IsBalanced_Solution(pRoot->right) : false;
}
int getDepth(TreeNode* pRoot){
if (pRoot == NULL)
return 0;
return 1 + max(getDepth(pRoot->left),getDepth(pRoot->right));
}
};
//后序递归版本
class Solution {
public:
bool IsBalanced_Solution(TreeNode* pRoot) {
if (pRoot == NULL){
return true;
}
int depth = 0;
return getDepth(pRoot,depth);
}
bool getDepth(TreeNode* pRoot, int &depth){//注意depth为传引用,传值出错
if(pRoot == NULL){
return true;
}
int ldepth = 0;//记录左子树高度
int rdepth = 0;//记录右子树高度
if(getDepth(pRoot->left, ldepth) && getDepth(pRoot->right,rdepth)){
int res = ldepth - rdepth;
if(res < -1 || res> 1){
return false;
}
if(res == -1) depth = rdepth + 1;
else depth = ldepth + 1;
return true;
}
return false;
}
};
//剪枝的版本,只要子树不平衡,那树就不是平衡树
class Solution {
public:
bool IsBalanced_Solution(TreeNode* pRoot) {
if (pRoot == NULL){
return true;
}
return getDepth(pRoot) == -1 ? false : true;
}
int getDepth(TreeNode* pRoot){
if(pRoot == NULL){
return 0;
}
int ldepth = 0, rdepth = 0;
if(pRoot->left != NULL){
ldepth = getDepth(pRoot->left);
if(ldepth == -1) return -1;
}
if(pRoot->right != NULL){
rdepth = getDepth(pRoot->right);
if(rdepth == -1) return -1;
}
return abs(ldepth - rdepth) <= 1? 1 + max(ldepth, rdepth) : -1;
}
};