首页 > 其他 > 详细

判断一棵树是否是二叉平衡树

时间:2018-07-27 21:32:30      阅读:102      评论:0      收藏:0      [点我收藏+]
主要就是判断二叉树深度进行改造。
判断条件为左树为平衡树,右树为平衡树,并且左树的高度和右树的高度插不超过-1;
public class IsAVL {
public static class Node{
private Node left;
private Node right;
private int value;
public Node(int value){
this.value = value;
}
}
public static int isAVL(Node head){
if(head==null){
return 0;
}
int leftdepth = isAVL(head.left);//左树深度
int rightdepth = isAVL(head.right);//右树深度
if(leftdepth==-1||rightdepth==-1){ //在后面设置,如果不符合则返回-1;
return -1;
}
int depth = Math.abs(leftdepth-rightdepth)>1?-1:leftdepth>rightdepth?leftdepth+1:rightdepth+1;
//如果左子树深度和右子树深度差超过1,则返回-1,否则返回两种之中大的那个,并且加一,
//加一是因为原来的子树的,现在的是父节点,需要加一。
return depth;
}
}
总结:二叉树深度,加递归的变形。

判断一棵树是否是二叉平衡树

原文:https://www.cnblogs.com/liuwentao/p/9379701.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!