打印AVL树数据的可能方法是什么?有可能用ANTLR来实现每个节点中的数据可视化,这样我也可以验证平衡吗?
谢谢!
答案 0 :(得分:0)
我在Java完成了这项工作,而不是JavaScript。但是,您只需要翻译语法。算法是一样的。假设你使用了指针,你的Node类看起来如下:
// However this would be implemented in JavaScript
public class BinarySearchTreeNode<K, V> {
BinarySearchTreeNode left;
BinarySearchTreeNode right;
K key;
V value;
}
这是我打印树的方式:
// This function starts it off at the root
// and calls the real function
public String toTreeString() {
return this.toTreeString("", true, "", root);
}
// Keep concatenating the string
private String toTreeString(String prefix, boolean top, String tree, BinarySearchTreeNode<K, V> node) {
BinarySearchTreeNode<K, V> left;
BinarySearchTreeNode<K, V> right;
String temp;
// If we were passed an empty tree
if (node == null) {
return "";
}
// Get children nodes
left = node.leftChild;
right = node.rightChild;
// If the right child is not null
if (right != null) {
// Draw a path to the node
temp = path(top, "" + prefix, "│ ", " ");
// Recursively append to right subtree
tree = toTreeString(temp, false, tree, right);
}
// Draw a path to this node
tree = path(top, tree + prefix, "└──", "┌──");
// Append this node to the tree
tree += " " + node.key + "\n";
// If the left child is not null
if (left != null) {
// Draw a path to the node
temp = path(top, "" + prefix, " ", "│ ");
// Recursively append left sub tree
tree = toTreeString(temp, true, tree, left);
}
return tree;
}
//------------------------------------------------------------------------------
private String path(boolean condition, String s, String choice1, String choice2) {
if (condition) {
s += choice1;
} else {
s += choice2;
}
return s;
}
一旦你有一个树构建,你就会传递
// Your implementation of AVL Tree
import structures.trees.AVLTree;
public final class Application {
public static void main(String[] args) {
AVLTree<Integer, Integer> tree = new AVLTree<>();
tree.insert(1, null);
tree.insert(4, null);
tree.insert(3, null);
tree.insert(0, null);
tree.insert(6, null);
tree.insert(9, null);
tree.insert(8, null);
tree.insert(3, null);
String treeString = tree.toTreeString();
System.out.println(treeString);
System.out.println("IsBalanced: " + tree.isBalanced());
}
}
输出:
│ ┌── 9
│ │ └── 8
│ ┌── 6
│ │ └── 4
└── 3
└── 1
└── 0
IsBalanced: true
如果您使用数组实现AVL树,则实现几乎为identical
然而:这只适用于小树。对于大树来说,阅读起来并不容易。您应该使用算法来检查树是否以编程方式平衡:
private int isBalanced(BinarySearchTreeNode<K, V> node) {
if (node == null)
return 0;
// Get heights of subtrees
int h1 = isBalanced(node.leftChild);
int h2 = isBalanced(node.rightChild);
if (h1 == -1 || h2 == -1)
return -1;
if (Math.abs(h1 - h2) > 1)
return -1;
if (h1 > h2)
return h1 + 1;
else
return h2 + 1;
}