题目描述
输入一棵二叉树,判断该二叉树是否是平衡二叉树。
解:/判断一颗二叉树是否为平衡二叉树
平衡二叉树的特点:(1)左小右大(2)左右子树的高度差不大于1
解法一:多次遍历节点求左右子树的高度。缺点在于重复遍历,例如首先遍历根结点1,那么根结点的的左子树2,,4,5,7遍历一遍;遍历左根结点2,那么4,5,7又会被遍历一遍。
int getDepth(TreeNode* pRoot)
{
if(!pRoot)
return 0;
int left=getDepth(pRoot->pLeft);
int right=getDepth(pRoot->pRight);
return (left>right) ? (left+1) : (right+1);
}
bool isBalancedTree1(TreeNode* pRoot)
{
if(!pRoot)
return true;
int left=getDepth(pRoot->pLeft);
int right=getDepth(pRoot->pRight);
int diff=left-right;
if(diff>1||diff<-1)
return false;
return isBalancedTree1(pRoot->pLeft)&&isBalancedTree1(pRoot->pRight);
}
解法二:后序遍历,每个节点只遍历一次,先遍历它的左右子树,看是否是平衡二叉树。
bool isBalanced(TreeNode* pRoot,int &depth) //注意 形参 depth是引用
{
if(!pRoot)
return true;
int Left=0,Right=0;
if(isBalanced(pRoot->left,Left)&&isBalanced(pRoot->right,Right))
{
int diff=Left-Right;
if(diff>=-1 && diff<=1){
depth=1+(Left>Right?Left:Right);
return true;
}
}
return false;
}
bool IsBalanced_Solution(TreeNode* pRoot)
{
int depth=0;
return isBalanced(pRoot,depth);
}
引用作为形参传入函数时,不做任何处理直接使用,形参是变量的别名。
而指针作为形参传入函数时,要为形参分配内存空间创建一个临时局部变量,并将实参指针的值复制到形参中。