完整代码示例-Java实现平衡二叉树的创建,遍历以及旋转
作者:互联网
结点类:
package DataStrcture.avltreedemo;
public class AVLTreeNode {
public AVLTreeNode leftNode;
public AVLTreeNode rightNode;
public int value;
//左旋转和右旋转
public void leftRotation() {
AVLTreeNode newNode = new AVLTreeNode(this.value);
newNode.leftNode = this.leftNode;
newNode.rightNode = this.rightNode.leftNode;
this.value = this.rightNode.value;
this.rightNode = this.rightNode.rightNode;
this.leftNode = newNode;
}
public void rightRotation() {
AVLTreeNode newNode = new AVLTreeNode(this.value);
newNode.leftNode = this.leftNode.rightNode;
newNode.rightNode = this.rightNode;
this.value = this.leftNode.value;
this.leftNode = this.leftNode.leftNode;
this.rightNode = newNode;
}
//得到二叉树的高度, 左子树的高度, 右子树的高度
public int height() {
return Math.max(leftNode == null ? 0 : leftNode.height(),
rightNode == null ? 0 : rightNode.height()) + 1;
}
public int leftHeight() {
if (this.leftNode != null)
return this.leftNode.height();
return 0;
}
public int rightHeight() {
if (this.rightNode != null)
return this.rightNode.height();
return 0;
}
//二叉树的创建(添加结点, 构建关系)
public void addNode(AVLTreeNode node) {
//左子树
if (node.value <= this.value) {
if (this.leftNode == null) {
this.leftNode = node;
} else {
this.leftNode.addNode(node);
}
//右子树
} else {
if (this.rightNode == null) {
this.rightNode = node;
} else {
this.rightNode.addNode(node);
}
}
}
//中序遍历
public void midOrder() {
if (this.leftNode != null) this.leftNode.midOrder();
System.out.println(this);
if (this.rightNode != null) this.rightNode.midOrder();
}
//构造器, toString
public AVLTreeNode(int val) {
this.value = val;
}
public String toString() {
return "Node{ value=" + value + "}";
}
}
平衡二叉树类:
package DataStrcture.avltreedemo;
public class AVLTreeDemo {
//初始化根节点
private AVLTreeNode root;
public AVLTreeDemo(AVLTreeNode node) {
this.root = node;
}
//测试方法
public static void main(String[] args) {
int arr[] = {10,9,11,6,5,7,8};
AVLTreeDemo tree = new AVLTreeDemo(null);
for (int x : arr) {
tree.add(new AVLTreeNode(x));
}
tree.midOrder();
System.out.println("平衡二叉树左子树的高度为: "+tree.root.leftHeight());
System.out.println("平衡二叉树右子树的高度为: "+tree.root.rightHeight());
}
//遍历二叉树
public void midOrder() {
if (root == null) {
System.out.println("二叉树为空, 遍历失败");
} else {
root.midOrder();
}
}
//添加结点到二叉树
public void add(AVLTreeNode node) {
if (root == null) {
root = node;
} else {
root.addNode(node);
//左旋转
if (root.leftHeight() - root.rightHeight() > 1) {
if (root.leftNode.rightHeight() - root.leftNode.leftHeight() > 0) {
root.leftNode.leftRotation();
}
//右旋转
root.rightRotation();
return;
}
if (root.rightHeight() - root.leftHeight() > 1) {
if (root.rightNode.leftHeight() - root.rightNode.rightHeight() > 0) {
root.rightNode.rightRotation();
}
root.leftRotation();
return;
}
}
}
}
标签:null,Java,示例,AVLTreeNode,rightNode,二叉树,leftNode,root,public 来源: https://blog.csdn.net/nmsLLCSDN/article/details/116834229