public class AVLTreeDemo {
public static void main(String[] args) {
int[] arr = {4, 3, 6, 5, 7, 8};
/*
4
/ \
3 6
/ \
5 7
\
8
*/
AVLTree tree = new AVLTree();
int len = arr.length;
for (int i = 0; i < len; i++) {
tree.add(new Node(arr[i]));
}
tree.infixOrder();
System.out.println("\n树的高度:"+tree.getRoot().height());
System.out.println("树的左子树高度:"+tree.getRoot().left.height());
System.out.println("树的右子树高度:"+tree.getRoot().right.height());
System.out.println("树的左右子树高度差的绝对值:" + tree.getRoot().differ());
}
}
class AVLTree {
private Node root;
public Node getRoot() {
return root;
}
public void setRoot(Node root) {
this.root = root;
}
public void infixOrder() {
if (root != null) {
root.infixOrder();
} else {
System.out.println("二叉树为空,无法遍历~");
}
}
public void add(Node node) {
if (root == null) {
root = node;
} else {
root.add(node);
}
}
}
class Node {
public int num;
public Node left;
public Node right;
public Node(int num) {
this.num = num;
}
@Override
public String toString() {
return num + "";
}
public void infixOrder() {
if (this.left != null) {
this.left.infixOrder();
}
System.out.print("=>" + num);
if (this.right != null) {
this.right.infixOrder();
}
}
/**
* 返回以该节点为根节点的树的高度
*/
public int height() {
return Math.max(this.left == null ? 0 : this.left.height(),
this.right == null ? 0 : this.right.height()) + 1;
}
/**
* 返回左子树的高度
*/
public int leftHeight() {
if (this.left == null) {
return 0;
} else {
return this.left.height();
}
}
/**
* 返回右子树的高度
*/
public int rightHeight() {
if (this.right == null) {
return 0;
} else {
return this.right.height();
}
}
/**
* 返回左右子树高度的差
*/
public int differ() {
return Math.abs(leftHeight() - rightHeight());
}
/**
* 添加新的节点【二叉排序树】
*/
public void add(Node node) {
if (node == null) {
return;
}
if (node.num < this.num) {
if (this.left != null) {
this.left.add(node);
} else {
this.left = node;
}
} else {
if (this.right != null) {
this.right.add(node);
} else {
this.right = node;
}
}
}
}
二叉树获取树的高度
最新推荐文章于 2021-10-07 20:01:45 发布