题目描述
输入一棵二叉树,判断该二叉树是否是平衡二叉树。
class Solution {
public:
bool IsBalanced_Solution(TreeNode* pRoot) {
bool res[]=new bool[1];
res[0]=true;
f(pRoot,1,res);
return res[0];
int f(TreeNode* pRoot,int level,bool res[]) {
if(pRoot==NULL) return level;
int lh=f(pRoot->left,level+1,res);
if(!res[0]) { return level; }
int rh=f(pRoot->right,level+1,res);
if(!res[0]) {return level;}
if(abs(lh-rh)>1) {
res[0]=false;
}
return max(lh,rh);
}
}
};
您的代码已保存
编译错误:您提交的代码无法完成编译
In file included from a.cc:2:
./solution.h:6:14: error: array initializer must be an initializer list
bool res[]=new bool[1];
感觉很傻比,根据左神的思路来写的代码,为什么写不对呢?!!!!!
参考简单思路:
class Solution {
public:
int f(TreeNode* pRoot) {
if(pRoot==NULL) return true;
int lh=f(pRoot->left);
int rh=f(pRoot->right);
return max(lh+1,rh+1);
}
bool IsBalanced_Solution(TreeNode* pRoot) {
if(pRoot==NULL) return true;
int left=f(pRoot->left);
int right=f(pRoot->right);
if(abs(left-right)>1)
return false;
return IsBalanced_Solution(pRoot->left)&&IsBalanced_Solution(pRoot->right);
}
};
//后续遍历二叉树,遍历过程中求子树高度,判断是否平衡
class Solution {
public:
bool IsBalanced(TreeNode *root, int & dep){
if(root == NULL){
return true;
}
int left = 0;
int right = 0;
if(IsBalanced(root->left,left) && IsBalanced(root->right, right)){
int dif = left - right;
if(dif<-1 || dif >1)
return false;
dep = (left > right ? left : right) + 1;
return true;
}
return false;
}
bool IsBalanced_Solution(TreeNode* pRoot) {
int dep = 0;
return IsBalanced(pRoot, dep);
}
};
class Solution {
public:
bool IsBalanced_Solution(TreeNode* pRoot) {
if(helper(pRoot) < 0) return false;
return true;
}
private:
int helper(TreeNode* node){
if(node == NULL) return 0;
int ld = helper(node->left);
if(ld == -1) return -1; //若左边已经不是平衡二叉树了,那就直接返回,没必要搜索右边了
int rd = helper(node->right);
if(rd == -1 || abs(ld-rd) > 1) return -1; //-1代表:不是平衡二叉树
return max(ld, rd)+1;
}
};
class Solution {
public:
bool IsBalanced_Solution(TreeNode* pRoot) {
return dfs(pRoot)<0?false:true;
}
int dfs(TreeNode *root){
if(!root) return 0;
int l=dfs(root->left),r=dfs(root->right);
if(l<0||r<0||abs(r-l)>1) return -1;
return 1+max(l,r);
}
};