题目
【输入一棵二叉树,判断该二叉树是否是平衡二叉树】
1、分析
- 平衡二叉树:如果某二叉树中任意节点的左、右子树深度相差不超过1,那么它就是一颗平衡二叉树。
- 可以使用递归的方式将每个节点的左右子树的深度进行遍历,再进行计算是否为平衡二叉树。
2、代码
class Solution {
public:
bool IsBalanced_Solution(TreeNode* pRoot) {
if(pRoot==nullptr)
return true;
int left=TreeDepth(pRoot->left);
int right=TreeDepth(pRoot->right);
int dis=abs(left-right);
if(dis<=1)
return true;
else
return false;
return IsBalanced_Solution(pRoot->left) && IsBalanced_Solution(pRoot->right);
}
int TreeDepth(TreeNode *pRoot)
{
if(pRoot==nullptr)
return 0;
int leftDep=TreeDepth(pRoot->left);
int rightDep=TreeDepth(pRoot->right);
return (leftDep>rightDep)?(leftDep+1):(rightDep+1);
}
};
改进的方法:
1、分析
由于之前的方法会重复的遍历一些节点从而影响了程序的性能,所以改进的方法是每个节点只遍历一次,在遍历的同时将其结果记录下来,方便下次直接使用,而无需再次遍历。
对于二叉树的深度,当使用后序遍历时,可以先遍历其子树,将其深度记录下来,这样下次可以直接使用。
2、代码
class Solution {
public:
bool IsBalanced_Solution(TreeNode* pRoot) {
int depth=0; //depth用来记录遍历过的子树的深度值,避免重复遍历
return IsBalanced(pRoot,&depth);
}
bool IsBalanced(TreeNode *pRoot, int *pDepth)
{
if(pRoot==nullptr)
{
*pDepth=0;
return true;
}
int leftDep,rightDep;
if(IsBalanced(pRoot->left,&leftDep) && IsBalanced(pRoot->right,&rightDep))
{
int dis=abs(leftDep-rightDep);
if(dis<=1)
{
*pDepth=1+(leftDep>rightDep?leftDep:rightDep);
return true;
}
}
return false;
}
};