判断一棵树是否是平衡二叉树
1.什么是平衡二叉树
平衡二叉树就是一个树的左子树和右子树的高度差不超过1 。如下图所示情况:
2.如何判断一棵树是否是平衡二叉树
(1)他的左子树是平衡二叉树
(2)他的右子树是平衡二叉树
(3)他的左子树和右子树高度差不超过1
3.接下来我们直接看代码
//树定义类
public class Node {
public int data;
public Node leftNode;
public Node rightNode;
public Node(int data) {
this.data=data;
}
public Node(int data, Node leftNode, Node rightNode) {
this.data = data;
this.leftNode = leftNode;
this.rightNode = rightNode;
}
}
//返回值定义类
public class ReturnType{
public boolean isBalanced;
public int height;
public ReturnType(boolean isBalanced,int height) {
this.isBalanced=isBalanced;
this.height=height;
}
}
//判断是否是平衡二叉树算法
//判断一棵树是否是平衡二叉树
public boolean isBalanced() {
return isBalanced(root);
}
public static boolean isBalanced(Node head) {
//返回这棵树是不是平衡二叉树
return process(head).isBalanced;
}
public static ReturnType process(Node x) {
//如果为空,则就是平衡二叉树
if(x==null) {
return new ReturnType(true,0);
}
//遍历当前子树的左子树
ReturnType leftData=process(x.leftNode);
//遍历当前子树的右子树
ReturnType rightData=process(x.rightNode);
//求当前这个子树的高度
int height=Math.max(leftData.height, rightData.height)+1;
//判断当前子树是否是平衡二叉树
boolean isBalanced=leftData.isBalanced && rightData.isBalanced && Math.abs(leftData.height-rightData.height)<2;
//返回true或者false以及高度
return new ReturnType(isBalanced,height);
}
//测试类(我这里测试了一颗平衡二叉树,大家可以自己测试)
public class Test {
public static void main(String[] args) {
Tree tree=new Tree();
Node node=new Node(6,new Node(4,new Node(3),new Node(5)),new Node(8,new Node(7),new Node(9)));
boolean c=tree.isBalanced(node);
System.out.println("这棵树是不是平衡二叉树:"+c);
}
}