题目描述:
输入一棵二叉树,判断该二叉树是否是平衡二叉树。
思路:(后续遍历)
使用深度优先搜索的后续遍历的的方法,因为后续遍历的遍历顺序是左右根的访问顺序,所以对于每个节点,首先判断子树是否是平衡二叉树,如果子树是平衡二叉树,记录此时该子树的深度(用于与其他子树后续其他的判断),如果不是则整个二叉树就不是平衡二叉树,下面使用递归的方式遍历。
代码:
class solution
{
public:
bool whetherBalanced(TreeNode* root)
{
int depth=0;
if(root)
return isBalanced(root,&depth)
return false;
}
bool isBalanced(TreeNode* p,int *depth)
{
if(!p)
return true;
int left=0;
int right=0;
if(isBalanced(p->left,&left)&&isBalanced(p->right,&right))
{
int diff=left-right;
if(diff>-1&&diff<1)
{
*depth=(left>right)?left+1:right+1;
return true;
}
}
return false;
}
}
class Solution {
public:
bool IsBalanced_Solution(TreeNode* pRoot) {
if(!pRoot)
return true;
return isBalanced(pRoot);
}
bool isBalanced(TreeNode* pRoot)
{
int left=depth(pRoot->left);
int right=depth(pRoot->right);
if(left-right>1||left-right<-1)
return false;
else
return true;
return isBalanced(pRoot->left)&&isBalanced(pRoot->right);
}
int depth(TreeNode* pRoot)
{
if(!pRoot)
return 0;
int left=depth(pRoot->left);
int right=depth(pRoot->right);
return left>right?left+1:right+1;
}
};