Java实现AVL平衡树
Posted Wecccccccc
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Java实现AVL平衡树相关的知识,希望对你有一定的参考价值。
代码如下:
package AVLTree;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.Queue;
import java.util.Scanner;
public class AVLTree {
private class TreeNode
{
private int data;
TreeNode left;
TreeNode right;
private int height;
public TreeNode(int e)
{
data = e;
left = null;
right = null;
height = 0;
}
}
private TreeNode AVLTreeRoot;
public AVLTree()
{
AVLTreeRoot = null;
}
public int heightTree(TreeNode root)
{
if (root==null) return 0;
int l = heightTree(root.left);
int r = heightTree(root.right);
return (l>r?l:r)+1;
}
private TreeNode singleLeftRotation(TreeNode root)
{
TreeNode p = root.left;
root.left = p.right;
p.right = root;
root.height = heightTree(root);
p.height = heightTree(p);
return p;
}
private TreeNode singleRightRotation(TreeNode root)
{
TreeNode p = root.right;
root.right = p.left;
p.left = root;
root.height = heightTree(root);
p.height = heightTree(p);
return p;
}
private TreeNode doubleLeftRightRotation(TreeNode root)
{
root.left = singleRightRotation(root.left);
return singleLeftRotation(root);
}
private TreeNode doubleRightLeftRotation(TreeNode root)
{
root.right = singleLeftRotation(root.right);
return singleRightRotation(root);
}
public TreeNode insertTree(int e,TreeNode root)
{
if (root==null)
{
root = new TreeNode(e);
}
else if (e < root.data)
{
root.left = insertTree(e,root.left);
if (heightTree(root.left)-heightTree(root.right)==2)
{
if (e < root.left.data)
{
root = singleLeftRotation(root);
}
else
{
root = doubleLeftRightRotation(root);
}
}
}
else if (e > root.data)
{
root.right = insertTree(e,root.right);
if (heightTree(root.left)-heightTree(root.right)==-2)
{
if (e > root.right.data)
{
root = singleRightRotation(root);
}
else
{
root = doubleRightLeftRotation(root);
}
}
}
root.height = heightTree(root);
return root;
}
public boolean createTree(int n)
{
Scanner sc = new Scanner(System.in);
for (int i = 0;i<n;i++)
{
int val = sc.nextInt();
AVLTreeRoot = insertTree(val,AVLTreeRoot);
}
return true;
}
public void levelOrder()
{
ArrayList<Integer> arrays = new ArrayList<>();
Queue<TreeNode> q = new LinkedList<>();
if (AVLTreeRoot==null)
{
System.out.println(arrays);
return ;
}
q.add(AVLTreeRoot);
while(!q.isEmpty())
{
TreeNode t = q.poll();
arrays.add(t.data);
if (t.left!=null) q.add(t.left);
if (t.right!=null) q.add(t.right);
}
System.out.println(arrays);
}
}
测试类如下:
package AVLTree;
public class TestAVLTree {
public static void main(String[] args)
{
AVLTree bt = new AVLTree();
bt.createTree(8);
bt.levelOrder();
}
}
以上是关于Java实现AVL平衡树的主要内容,如果未能解决你的问题,请参考以下文章
java项目---用java实现二叉平衡树(AVL树)并打印结果(详)