I want to create a binary tree with random numbers. For that I have a function that generates the tree and a function that generates the random numbers. As instance variables i have following:
private static final int MIN_VALUE = 1;
private static final int MAX_VALUE = 100;
private static LinkedBinaryTree<Integer> tree = new LinkedBinaryTree<>();
private static Random random = new Random();
I think it doesn't look "beautiful" with all the generateRandomInt calls. Is there a way to shorten this or make it more efficient? Is there also a way to create randomly a binary tree (number of nodes)? I have the methods following methods to add something to a tree:
addRoot(value)
insertLeftChild(node, value)
insertRightChild(node, value)
insertChild(node, value)
insertChildren(node, value1, value2)
addRoot adds a root node insertLeftChild and insertRightChild add a left or right child to node insertChild does the same, but it checks if left or right child is free insertChildren adds a left and a right child at the same time to node
public static int generateRandomInt(int MIN_VALUE, int MAX_VALUE) {
return random.nextInt((MAX_VALUE - MIN_VALUE) + 1) + MIN_VALUE;
}
public static void generateBinaryTree() {
Position<Integer> root = tree.addRoot(generateRandomInt(MIN_VALUE, MAX_VALUE));
Position<Integer> child1 = tree.insertChild(root, generateRandomInt(MIN_VALUE, MAX_VALUE));
Position<Integer> child2 = tree.insertChild(root, generateRandomInt(MIN_VALUE, MAX_VALUE));
Position<Integer> child3 = tree.insertChild(child1, generateRandomInt(MIN_VALUE, MAX_VALUE));
Position<Integer> child4 = tree.insertChild(child1, generateRandomInt(MIN_VALUE, MAX_VALUE));
Position<Integer> child5 = tree.insertChild(child2, generateRandomInt(MIN_VALUE, MAX_VALUE));
Position<Integer> child6 = tree.insertChild(child2, generateRandomInt(MIN_VALUE, MAX_VALUE));
tree.insertChildren(child3, generateRandomInt(MIN_VALUE, MAX_VALUE), generateRandomInt(MIN_VALUE, MAX_VALUE));
tree.insertChildren(child4, generateRandomInt(MIN_VALUE, MAX_VALUE), generateRandomInt(MIN_VALUE, MAX_VALUE));
tree.insertChildren(child5, generateRandomInt(MIN_VALUE, MAX_VALUE), generateRandomInt(MIN_VALUE, MAX_VALUE));
tree.insertChildren(child6, generateRandomInt(MIN_VALUE, MAX_VALUE), generateRandomInt(MIN_VALUE, MAX_VALUE));
}
Aucun commentaire:
Enregistrer un commentaire