JAVA判断二叉树是否是二叉平衡树

本文介绍了一个简单的Java程序,用于创建二叉树并判断其是否为平衡二叉树。通过递归方法计算树的层数,并检查每个节点的左右子树高度差是否不超过1来实现平衡性的验证。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

import java.util.*;      

public class BinaryTree {
protected Node root;

public BinaryTree(Node root) {
this.root = root;
}

public Node getRoot() {
return root;
}

/** 构造树 */
public static Node init() {
Node a = new Node('A');
Node b = new Node('B', null, a);
Node c = new Node('C');
Node d = new Node('D', b, c);
Node e = new Node('E');
Node f = new Node('F', e, null);
Node g = new Node('G', null, f);
Node h = new Node('H', d, g);
return h;// root
}

/**
* 返回树的层数
*
* @param p
* @return
*/
public static int h(Node p) {

if (p == null)
return -1;
return 1 + Math.max(h(p.getLeft()), h(p.getRight()));// 返回较大的
}

/**
* 检查是否是平衡树
*
* @param p
* @return
*/
public static boolean checkAVL(Node p) {

if (p == null)
return true;
// 左子树与右子树绝对值不能超过 1,并且左右子树也是平衡二叉树
return (Math.abs(h(p.getLeft()) - h(p.getRight())) <= 1 && checkAVL(p.getLeft()) && checkAVL(p.getRight()));

}


/**
* @param args
*/
public static void main(String[] args) {
BinaryTree tree = new BinaryTree(init());

System.out.println("是否是平衡树");
System.out.println(checkAVL(tree.getRoot()));
}



}
class Node {
private char key;
private Node left, right;

public Node(char key) {
this(key, null, null);
}

public Node(char key, Node left, Node right) {
this.key = key;
this.left = left;
this.right = right;
}

public char getKey() {
return key;
}

public void setKey(char key) {
this.key = key;
}

public Node getLeft() {
return left;
}

public void setLeft(Node left) {
this.left = left;
}

public Node getRight() {
return right;
}

public void setRight(Node right) {
this.right = right;
}
}


C:\ex>java BinaryTree
是否是平衡树
false

[img]http://dl.iteye.com/upload/attachment/0072/3033/114e5346-bf3e-3bf5-b696-7bfbf260a382.gif[/img]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值