判断二叉树是不是平衡二叉树 ,使用递归解法。
平衡二叉树有个特点,就是左右子树之差绝对值不能大于1,所以需要借助二叉树深度,之前求出过二叉树深度
(1)如果二叉树为空,返回真
(2)如果二叉树不为空,如果左子树和右子树都是AVL树并且左子树和右子树高度相差不大于1,返回真,否则返回假
package cn.edu.nwu.tree;
/**
* @author jcm
*
*时间 2016年9月16日
*/
public class TreeNodeIsAVL {
public static void main(String[] args) {
TreeNode root = CreateBinaryTree.createTreeNode();
System.out.println(isVALRecursion(root));
}
/**
* @author jcm
* 判断二叉树是不是平衡二叉树 ,平衡二叉树有个特点,就是左右子树之差绝对值不能大于1,所以需要借助二叉树深度,之前求出过二叉树深度
* (1)如果二叉树为空,返回真
* (2)如果二叉树不为空,如果左子树和右子树都是AVL树并且左子树和右子树高度相差不大于1,返回真,否则返回假
* @param root
* @return
*/
private static boolean isVALRecursion(TreeNode root) {
if(root == null){
return true;
}
//求解左子树和右子树深度
int leftDepth = GetTreeNodeDepth.getTreeNodeDepth(root.leftChild);
int rightDepth = GetTreeNodeDepth.getTreeNodeDepth(root.rightRight);
//左右子树绝对值之差,如果之差大于1,直接返回false
int diff = Math.abs(leftDepth-rightDepth);
if(diff > 1){
return false;
}
return isVALRecursion(root.leftChild) && isVALRecursion(root.rightRight);
}
}