package tree;
public class AVLTree {
private static TreeNode root;
public static void inOrder() {
if (root != null) {
root.inOrder();
} else {
System.out.println("Tree is empty");
}
}
public static void addNode(TreeNode node) {
if (root == null) {
root = node;
} else {
root.addNode(node);
}
}
public static void main(String[] args) {
int[] arr = {3, 5, 1, 13, 9, 4, 5, 11};
AVLTree tree = new AVLTree();
for (int i : arr) {
tree.addNode(new TreeNode(i));
}
//测试添加
tree.inOrder();
}
}
class TreeNode {
int value;
TreeNode left;
TreeNode right;
public TreeNode(int value) {
this.value = value;
}
public void inOrder() {
if (this.left != null) {
this.left.inOrder();
}
System.out.println(this);
if (this.right != null) {
this.right.inOrder();
}
}
//返回以当前节点作为根节点的树的高度
public int height() {
return Math.max((left == null ? 0 : left.height()), (right == null ? 0 : right.height())) + 1;
}
//左旋
private void leftRotate() {
//新建一个节点,节点的值为当前节点的值
TreeNode newNode = new TreeNode(value);
//将新节点的左子树设置为当前节点的左子树
newNode.left = left;
//将新节点的右子树设置为当前子树的右子树的左子树
newNode.right = right.left;
//将当前节点的值赋为右子节点的值
value = right.value;
//将当前节点的右子树设置为右子树的右子树
right = right.right;
//将当前节点的左子树设置为新节点
left = newNode;
}
//右旋
private void rightRotate() {
//创建新节点,值为当前节点的值
TreeNode newNode = new TreeNode(value);
//将新节点的右子树设置为当前节点的右子树
newNode.right = right;
//将新节点的左子树设置为当前节点的左子树的右子树
newNode.left = left.right;
//将当前节点的值设置为左子树的值
value = left.value;
//将当前节点的左子树设置为左子树的左子树
left = left.left;
//将当前节点的右子树设置为新节点
right = newNode;
}
//添加节点:
public void addNode(TreeNode node) {
if (this.value < node.value) {//传入节点的值大于当前节点值
if (this.right == null) {//当前节点的右子节点为空,将传入节点挂在右子节点
this.right = node;
} else {//向右子树递归添加节点
this.right.addNode(node);
}
} else {//传入节点的值小于等于当前节点
if (this.left == null) {//当前节点的左子节点为空,将传入节点挂在左子节点
this.left = node;
} else {//向左子树递归添加节点
this.left.addNode(node);
}
}
//当添加完节点后,判断左右子树的高度
int leftHeight = left == null ? 0 : left.height();
int rightHeight = right == null ? 0 : right.height();
if(leftHeight - rightHeight > 1){
//左子树的高度大于右子树,进行右旋.在右旋之前得先保证左子树的左子树比左子树的右子树大
if(left != null && (left.left == null ? 0 : left.left.height()) < (left.right == null ? 0 : left.right.height())){
//如果左子树的右子树高度大于左子树的左子树高度,先将左子树左旋
left.leftRotate();
}
rightRotate();
}else if(rightHeight - leftHeight > 1){
//右子树的高度比左子树高度高出1, 进行左旋.在左旋之前得先保证右子树的右子树比右子树的左子树高
if(right != null && (right.right == null ? 0 : right.right.height()) < (right.left == null ? 0 : right.left.height())){
//如果右子树的左子树高度大于右子树的右子树高度,先将右子树右旋
right.rightRotate();
}
leftRotate();
}
}
@Override
public String toString() {
return "TreeNode{" +
"value=" + value +
'}';
}
}
数据结构与算法(十二)构建平衡二叉树(左旋、右旋)
最新推荐文章于 2023-01-09 12:38:57 发布