检查二叉树是否平衡

惊恐实现一个函数,检查二叉树是否平衡。在这个问题中。平衡树的定义例如以下:随意一个结点。其两棵子树的高度差不超过1.

              直接递归訪问整棵树,计算每一个结点两棵子树的高度。

public static int getHeight(TreeNode root)
{
if(root == null) return 0;//终止条件
return Math.max(getHeight(root.left), getHeight(root.right))+1;
}
public static boolean isBalanced(TreeNode root)
{
if(root == null) return true;//终止条件
int heightDiff=getHeight(root.left)-getHeight(root.right);
if(Math.abs(heightDiff)>1)
return false;
else//递归
{
return isBalanced(root.left) && isBalanced(root.right); 

}
}


public static int checkHeight(TreeNode root )
{
if(root == null)
{
return 0;//高度为0
}
//检查左子树是否平衡
int leftHeight=checkHeight(root.left);
if(leftHeight==-1)
{
return -1;
}
//检查右子树是否平衡
int rightHeight=checkHeight(root.right);
if(rightHeight == -1)
{
return -1;
}

/*检查当前结点是否平衡*/

int heightDiff=leftHeight-rightHeight;

if(Math.abs(heightDiff)>1)

      return -1;

else
{
//返回高度
     return Math.max(leftHeight, rightHeight)+1;
}
}

public static boolean isBalanced(TreeNode root)
{
if(checkHeight(root)== -1)
{
return false;
}
else
{
return true;
}
}

这段代码须要O(N)的时间和O(H)的空间,H是树的高度。

原文地址:https://www.cnblogs.com/blfbuaa/p/7089904.html