题目:
输入一课二叉树的根结点,判断该树是不是平衡二叉树。如果二叉树中任意结点的左右子树的深度相差不超过1,那么它就是一棵平衡二叉树。
思路:
1、重复遍历结点
参考上一题求二叉树的深度,先求出根结点的左右子树的深度,然后判断它们的深度相差不超过1,如果否,则不是一棵二叉树;如果是,再用同样的方法分别判断左子树和右子树是否为平衡二叉树,如果都是,则这就是一棵平衡二叉树。
但上面的方法在判断子树是否为平衡二叉树时,会重复遍历树的结点,不断地求子树的深度,所以效率不高。
2、遍历一遍结点
我们在遍历结点的同时记录下该结点的深度,这样就可以避免了重复访问。
代码:
方法1:
struct TreeNode{
int val;
TreeNode* left;
TreeNode* right;
}; int TreeDepth(TreeNode* pRoot){
if(pRoot==NULL)
return 0;
int left=TreeDepth(pRoot->left);
int right=TreeDepth(pRoot->right);
return left>right?(left+1):(right+1);
} bool IsBalanced(TreeNode* pRoot){
if(pRoot==NULL)
return true;
int left=TreeDepth(pRoot->left);
int right=TreeDepth(pRoot->right);
int diff=left-right;
if(diff>1 || diff<-1)
return false;
return IsBalanced(pRoot->left) && IsBalanced(pRoot->right);
}
方法2:
bool IsBalanced_1(TreeNode* pRoot,int& depth){
if(pRoot==NULL){
depth=0;
return true;
}
int left,right;
int diff;
if(IsBalanced_1(pRoot->left,left) && IsBalanced_1(pRoot->right,right)){
diff=left-right;
if(diff<=1 || diff>=-1){
depth=left>right?left+1:right+1;
return true;
}
}
return false;
} bool IsBalancedTree(TreeNode* pRoot){
int depth=0;
return IsBalanced_1(pRoot,depth);
}
在线测试OJ:
http://www.nowcoder.com/books/coding-interviews/8b3b95850edb4115918ecebdf1b4d222?rp=2
AC代码:
class Solution {
public:
bool IsBalanced_Solution(TreeNode* pRoot) {
if(pRoot==NULL)
return true;
int left=TreeDepth(pRoot->left);
int right=TreeDepth(pRoot->right);
int diff=left-right;
if(diff>1 || diff<-1)
return false;
return IsBalanced_Solution(pRoot->left) && IsBalanced_Solution(pRoot->right);
} int TreeDepth(TreeNode* pRoot){
if(pRoot==NULL)
return 0;
int left=TreeDepth(pRoot->left);
int right=TreeDepth(pRoot->right);
return left>right?(left+1):(right+1);
}
};
class Solution {
public:
bool IsBalanced_Solution(TreeNode* pRoot) {
int depth=0;
return IsBalanced(pRoot,depth);
} bool IsBalanced(TreeNode* pRoot,int& depth){
if(pRoot==NULL){
depth=0;
return true;
}
int left,right,diff;
if(IsBalanced(pRoot->left,left) && IsBalanced(pRoot->right,right)){
diff=left-right;
if(diff<=1 && diff>=-1){
depth=left>right?left+1:right+1;
return true;
}
}
return false;
}
};