Index Out Of Bound Exception Error - java

I've been working on trying to fix this error for a few hours and i cant figure out where/what is causing the error
(java.lang.IndexOutOfBoundsException: index:68 size: 26)
this creates the alphabet in all caps
String [] myStringsChars= new String[26];
for(int i = 0; i < 26; i++)
{
myStringsChars[i] = new String(Character.toChars(i+65));
System.out.println(myStringsChars[i]);
}
i suspect the cause of the problem is one of these two loops
adds array letters to a linked list and sets it as a node
int j=0;
while (j<myStringsChars.length){
BinaryTree.add(alphabet = new TreeNode(myStringsChars[j]));
if (j<=26){
j++;
}
}
sets the node parents and children
int k =0;
while (k<BinaryTree.size()){
int find=(k-1)/2;
BinaryTree.get(k).setParent(BinaryTree.get(find));
if(k%2 ==0){
(BinaryTree.get(k).getParent()). setRightChild(BinaryTree.get(k));
}
else{
(BinaryTree.get(k).getParent()).setLeftChild(BinaryTree.get(k));
}
k++;
}
here's the rest of my code in case it helps
import java.util.*;
public class TreeExercise
{
public static void main(String args[])
{
String [] myStringsChars= new String[26];
for(int i = 0; i < 26; i++)
{
myStringsChars[i] = new String(Character.toChars(i+65));
System.out.println(myStringsChars[i]);
}
List<TreeNode> BinaryTree = new LinkedList();
int j=0;
while (j<myStringsChars.length){
BinaryTree.add(alphabet = new TreeNode(myStringsChars[j]));
if (j<=26){
j++;
}
}
int k =0;
while (k<BinaryTree.size()){
int find=(k-1)/2;
BinaryTree.get(k).setParent(BinaryTree.get(find));
if(k%2 ==0){
(BinaryTree.get(k).getParent()). setRightChild(BinaryTree.get(k));
}
else{
(BinaryTree.get(k).getParent()).setLeftChild(BinaryTree.get(k));
}
k++;
}
BinaryTree.get(0).setParent(null);
Scanner input= new Scanner(System.in);
String userChoice="";
while (!(userChoice.equals("end"))){
System.out.println("enter two CAPITAL letters to find their common ancestor ex.(DC)\n type 'end' to end program");
userChoice= input.nextLine();
char letter1=userChoice.charAt(0);
char letter2=userChoice.charAt(1);
int let1= (int)letter1;
int let2= (int)letter2;
if(userChoice.length()<=2){
// cant find BinaryTree ERROR
TreeNode commonAncestor= findLowestCommonAncestor(root, BinaryTree.get(let1), BinaryTree.get(let2));
if (commonAncestor !=null){
System.out.println(commonAncestor.getContents());
}
System.out.println("Result is: " + "D");
}
else if (userChoice.equals("end")){
System.exit(0);
}
else{
System.out.println("you must type in 2 capital letters");
userChoice=input.nextLine();
}
}
}
public static TreeNode findLowestCommonAncestor(TreeNode root, TreeNode node1, TreeNode node2)
{
findLowestCommonAncestor(root.getRightChild(), node1, node2)
//every time
TreeNode rightChild= findLowestCommonAncestor(root.getRightChild(), node1, node2);
TreeNode leftChild= findLowestCommonAncestor(root.getLeftChild(), node1, node2);
if (leftChild != null && rightChild!=null){
return root;
}
if(root==null){
return null;
}
if (leftChild!=null){
return leftChild;
}
if(root.getContents()==node1 || root.getContents()==node2){
return root;
}
else {
return rightChild;
}
}
}
TreeNode nodes
public class TreeNode<T extends Comparable>{
private T contents;
private TreeNode<T> parent;
private TreeNode<T> leftChild;
private TreeNode<T> rightChild;
private int level;
public TreeNode()
{
//added
//parent=null;
//leftChild=null;
//rightChild=null;
//level=0;
}
public TreeNode(T data){
contents=data;
this.parent=parent;
}
public TreeNode(T data, TreeNode parent)
{
contents = data;
this.parent = parent;
}
public void setLeftChild(TreeNode node)
{
this.leftChild = node;
}
public void setRightChild(TreeNode node)
{
this.rightChild = node;
}
public boolean isContentEquals(T data)
{
return 0 == getContents().compareTo(data);
}
/**
* #return the contents
*/
public T getContents() {
return contents;
}
/**
* #param contents the contents to set
*/
public void setContents(T contents) {
this.contents = contents;
}
/**
* #return the parent
*/
public TreeNode getParent() {
return parent;
}
/**
* #param parent the parent to set
*/
public void setParent(TreeNode parent) {
this.parent = parent;
}
/**
* #return the leftChild
*/
public TreeNode getLeftChild() {
return leftChild;
}
/**
* #return the rightChild
*/
public TreeNode getRightChild() {
return rightChild;
}
/**
* Given an object T contentToSearch, this method returns
* the node that stores the contentToShare or null if not found on the current tree
* #return the node
*/
public TreeNode findNodeOnTree(T contentToSearch)
{
List<TreeNode> nodes = new LinkedList();
nodes.clear();
nodes.add(this);
while(!nodes.isEmpty())
{
TreeNode current = nodes.remove(0);
if(current.isContentEquals(contentToSearch))
{
return current;
}
if(current.leftChild != null)
{
nodes.add(current.leftChild);
}
if(current.rightChild != null)
{
nodes.add(current.rightChild);
}
}
return null;
}
/**
* #return the level
*/
public int getLevel() {
return level;
}
/**
* #param level the level to set
*/
public void setLevel(int level) {
this.level = level;
}
}

Your error appears to be here, guessing that this is line TreeExercise.java:113:
int let1= (int)letter1;
int let2= (int)letter2;
if(userChoice.length()<=2){
// cant find BinaryTree ERROR
TreeNode commonAncestor= findLowestCommonAncestor(root,
BinaryTree.get(let1), BinaryTree.get(let2));
^^^^ ^^^^
Your tree list is indexed from 0 to 25, but let1 and let2, given an input of DE, are 68 and 69. So, try:
int let1= (int)letter1 - 'A';
int let2= (int)letter2 - 'A';
It would be clearer in your other code, too, to use 'A' rather than 65.

Related

Transferring a String array to Binary Tree

I'm trying to write a method that can transfer an array into a Binary tree. I know the code is not right, I run it and hope it would show something that I can continue to fix it. But it just kept loading without any error or result. May anyone give me some advice, please!
Here is the BST class:
public class BSTNode {
private String data;
private BSTNode left;
private BSTNode right;
public BSTNode(String data) {
this.data = data;
this.right = null;
this.left = null;
}
public String getData() {
return data;
}
public void setData(String data) {
this.data = data;
}
public BSTNode getLeft() {
return left;
}
public void setLeft(BSTNode left) {
this.left = left;
}
public BSTNode getRight() {
return right;
}
public void setRight(BSTNode right) {
this.right = right;
}
}
And my method:
public BSTNode fromArray(String[] array, int start, int end) {
int i = start;
BSTNode root = new BSTNode(array[i]);
BSTNode current = root;
BSTNode parent = null;
while (i <= end) {
if (array[i].compareTo(current.getData()) < 0) {
parent = current;
current.setLeft(current); //Should I put current.setLeft(root) here?
} else {
parent = current;
current.setRight(current);
}
// Create the new node and attach it to the parent node
if (array[i].compareTo(parent.getData()) < 0) {
parent.setLeft(new BSTNode(array[i]));
} else {
parent.setRight(new BSTNode(array[i]));
}
i++;
}
return current;
}
Thank you for your time!
After you've initialized the root, you've already inserted the first element, so you can increment i right away.
You set the left and right pointers without keeping track of the prior value.
You never change the value of current within the loop, and, as you immediately assign it to parent, you don't change parent either.
You should return the root instead of the current node.
How about something like this:
while (++i <= end) {
current = root;
while (current != null) {
parent = current;
if (array[i].compareTo(current.getData()) < 0) {
current = current.getLeft();
} else {
current = current.getRight();
}
}
// Create the new node and attach it to the parent node
if (array[i].compareTo(parent.getData()) < 0) {
parent.setLeft(new BSTNode(array[i]));
} else {
parent.setRight(new BSTNode(array[i]));
}
}
return root;
UPDATE:
You can avoid a redundant comparison by keeping its result in a variable:
while (++i <= end) {
boolean left;
current = root;
do {
parent = current;
left = array[i].compareTo(current.getData()) < 0;
if (left) {
current = current.getLeft();
} else {
current = current.getRight();
}
} while (current != null);
// Create the new node and attach it to the parent node
if (left) {
parent.setLeft(new BSTNode(array[i]));
} else {
parent.setRight(new BSTNode(array[i]));
}
}
return root;
public class Main {
public static final class Node {
public static final String NULL = "_";
public static final String SPLIT = ",";
private final String val;
private Node left;
private Node right;
public Node(String val) {
this.val = val;
}
}
public static void main(String... args) {
Node root = createBinaryTree();
String str = serialize(root); // 0,1,3,7,_,9,_,_,_,4,_,_,2,5,_,8,_,_,6,_,_
Node newRoot = deserialize(str);
}
private static String serialize(Node root) {
StringBuilder buf = new StringBuilder();
serialize(root, buf);
return buf.toString();
}
private static void serialize(Node node, StringBuilder buf) {
if (buf.length() > 0)
buf.append(Node.SPLIT);
if (node == null)
buf.append(Node.NULL);
else {
buf.append(node.val);
serialize(node.left, buf);
serialize(node.right, buf);
}
}
private static Node deserialize(String str) {
String[] values = str.split(Node.SPLIT);
return deserialize(values, new AtomicInteger());
}
private static Node deserialize(String[] values, AtomicInteger i) {
if (i.get() >= values.length)
return null;
String value = values[i.getAndIncrement()];
if (Node.NULL.equalsIgnoreCase(value))
return null;
Node node = new Node(value);
node.left = deserialize(values, i);
node.right = deserialize(values, i);
return node;
}
/*
* 0
* / \
* 1 2
* / \ / \
* 3 4 5 6
* / \
* 7 8
* \
* 9
*/
private static Node createBinaryTree() {
Node[] nodes = { new Node("0"), new Node("1"), new Node("2"), new Node("3"),
new Node("4"), new Node("5"), new Node("6"), new Node("7"),
new Node("8"), new Node("9") };
nodes[0].left = nodes[1];
nodes[0].right = nodes[2];
nodes[1].left = nodes[3];
nodes[1].right = nodes[4];
nodes[2].left = nodes[5];
nodes[2].right = nodes[6];
nodes[3].left = nodes[7];
nodes[5].right = nodes[8];
nodes[7].right = nodes[9];
return nodes[0];
}
}

Implement the tree in java? not hard coded

There is a Tree implementation, which requires the correction and idea of how to implement the logic.
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
/**
* #param <T>
*/
class TreeNode<T> implements Iterable<TreeNode<T>> {
private final List<TreeNode<T>> elementsIndex;
public T data;
public TreeNode<T> parent;
public List<TreeNode<T>> children;
/**
* #param data
*/
public TreeNode(T data) {
this.data = data;
this.children = new LinkedList<TreeNode<T>>();
this.elementsIndex = new LinkedList<TreeNode<T>>();
this.elementsIndex.add(this);
}
/**
* #param depth
* #return Indentation
*/
private static String createIndent(int depth) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < depth; i++) {
sb.append('-');
}
return sb.toString();
}
/**
* #return parent
*/
public boolean isRoot() {
return parent == null;
}
/**
* #return check the size of child
*/
public boolean isLeaf() {
return children.size() == 0;
}
/**
* #param child
* #return child node
*/
public TreeNode<T> addChild(T child) {
TreeNode<T> childNode = new TreeNode<T>(child);
childNode.parent = this;
this.children.add(childNode);
this.registerChildForSearch(childNode);
return childNode;
}
/**
* #return the depth of the level
*/
public int getLevel() {
if (this.isRoot())
return 0;
else
return parent.getLevel() + 1;
}
/**
* #param node
*/
private void registerChildForSearch(TreeNode<T> node) {
elementsIndex.add(node);
if (parent != null)
parent.registerChildForSearch(node);
}
/**
* #param cmp
* #return finds the element
*/
public TreeNode<T> findTreeNode(Comparable<T> cmp) {
for (TreeNode<T> element : this.elementsIndex) {
T elData = element.data;
if (cmp.compareTo(elData) == 0)
return element;
}
return null;
}
/**
* #return the root
*/
#Override
public String toString() {
return data != null ? data.toString() : "[data null]";
}
/**
* #return iterator
*/
#Override
public Iterator<TreeNode<T>> iterator() {
TreeNodeIter<T> iter = new TreeNodeIter<T>(this);
return iter;
}
/**
* #param treeRoot
* #param data
* #return the data else null if not found
*/
public TreeNode<T> search(TreeNode<T> treeRoot, T data) {
Comparable<T> searchCriteria = new Comparable<T>() {
#Override
public int compareTo(Object treeData) {
if (treeData == null)
return 1;
boolean nodeOk = treeData.equals(data);
return nodeOk ? 0 : 1;
}
};
TreeNode<T> found = treeRoot.findTreeNode(searchCriteria);
return found;
}
/**
* #param treeRoot
* #return the whole tree
*/
public StringBuilder display(TreeNode<T> treeRoot) {
StringBuilder print = new StringBuilder();
print.append('\n');
for (TreeNode<T> node : treeRoot) {
String indent = createIndent(node.getLevel());
print.append(indent + node.data);
print.append("\n|");
}
if (print.length() > 0)
print.deleteCharAt(print.length() - 1);
return print;
}
}
/**
* #param <T>
*/
class TreeNodeIter<T> implements Iterator<TreeNode<T>> {
private final TreeNode<T> treeNode;
private final Iterator<TreeNode<T>> childrenCurNodeIter;
private ProcessStages doNext;
private TreeNode<T> next;
private Iterator<TreeNode<T>> childrenSubNodeIter;
/**
* #param treeNode
*/
public TreeNodeIter(TreeNode<T> treeNode) {
this.treeNode = treeNode;
this.doNext = ProcessStages.ProcessParent;
this.childrenCurNodeIter = treeNode.children.iterator();
}
/**
* #return true if there is nay element
*/
#Override
public boolean hasNext() {
if (this.doNext == ProcessStages.ProcessParent) {
this.next = this.treeNode;
this.doNext = ProcessStages.ProcessChildCurNode;
return true;
}
if (this.doNext == ProcessStages.ProcessChildCurNode) {
if (childrenCurNodeIter.hasNext()) {
TreeNode<T> childDirect = childrenCurNodeIter.next();
childrenSubNodeIter = childDirect.iterator();
this.doNext = ProcessStages.ProcessChildSubNode;
return hasNext();
} else {
this.doNext = null;
return false;
}
}
if (this.doNext == ProcessStages.ProcessChildSubNode) {
if (childrenSubNodeIter.hasNext()) {
this.next = childrenSubNodeIter.next();
return true;
} else {
this.next = null;
this.doNext = ProcessStages.ProcessChildCurNode;
return hasNext();
}
}
return false;
}
/**
* #return the next element
*/
#Override
public TreeNode<T> next() {
return this.next;
}
#Override
public void remove() {
throw new UnsupportedOperationException();
}
enum ProcessStages {
ProcessParent,
ProcessChildCurNode,
ProcessChildSubNode
}
}
So, the issue is that I have the data something like this
Gen
|-Test1
|--Mat
|-Test2
|--123
|---Child's Child
|----Child's Child's Child
|----2406
|-Test3
|--24
But to implement that I have to hard code something like this
public static TreeNode<String> getSet() {
TreeNode<String> root = new TreeNode<String>("Gen");
{
TreeNode<String> node0 = root.addChild("Test1");
{
TreeNode<String> node00 = node0.addChild("Mat");
}
TreeNode<String> node1 = root.addChild("Test2");
{
TreeNode<String> node10 = node1.addChild("123");
{
TreeNode<String> node100 = node10.addChild("Child's Child");
{
TreeNode<String> node1000 = node100.addChild("Child's Child's Child");
TreeNode<String> node1001 = node100.addChild("2406");
}
}
}
TreeNode<String> node2 = root.addChild("Test3");
{
TreeNode<String> node20 = node2.addChild("24");
}
}
return root;
}
}
On the top that I have the helper method called getPartentChildPart() method which is used to get the
Map<Parent, List> that is Map<String,List<String>>
Gen
|-Test1
|--Mat
|-Test2
|--123
|---Child's Child
|----Child's Child's Child
|----2406
|-Test3
|--24
For example, if I gave Gen as the parameter to getPartentChildPart() then it will return
Map<Gen,<Test1,Test2,Test3>>
So far what I can achieve is this
public void Build(Map<String, List<String>> ROOT) {
TreeNode<String> root = null;
TreeNode<String> node = null;
for (Map.Entry<String, List<String>> i : ROOT.entrySet()) {
root = new TreeNode<>(i.getKey());
for (String j : i.getValue())
{
node = root.addChild(j);
parent = getPartentChildPart(j);
Build(parent);
}
System.out.println("Root"+root.display(root));
}
}
public void Show() {
Map<String, List<String>> rt = null;
rt = getPartentChildPart("Gen");
Build(rt);
}
The result what I get this is
Gen
|-Test1
|-Test2
|-Test3
I don't understand why recursion is not working and how can I implement this... Although if I hardcode this it can work what if my tree grows in future then hard code will not work.
The first thing to do would be to add a method that returns your list of children. From there recursion becomes quite simple.
void itChildren(TreeNode<T> node)
{
// do stuff
if (!node.getChildren().isEmpty())
{
for (int i = 0; i < node.getChildren().size(); i++)
{
itChildren(node.getChildren().get(i));
}
}
// do stuff
}
This would then iterate over the entirety of the tree. Depending on whether you want to do things before (which I believe is your case) or after the children you can place your code either at the top or bottom of the function.
Let me know if this works for you.
final TreeNode<String> struct = "Gen";
public void build(Map<String, List<String>> parentRoot, TreeNode<String> node) {
Map<String, List<String>> parent;
for (Map.Entry<String, List<String>> i : parentRoot.entrySet()) {
for (Stringj : i.getValue()) {
TreeNode<String> childNode = node.addChild(new TreeNode<>(j));
parent = getPartentChildPart(j);
build(parent, childNode);
}
}
}
public void show() {
Map<String, List<String>> ROOT = null;
ROOT = getPartentChildPart("Gen");
build(ROOT, struct);
System.out.println(struct.display(struct));
}
The mistake was that I need to create a new node every time and need to get the root outside the recurrsion.

Iterator implement on AVL tree java

I'm trying to implement iterator on AVL tree, I'm stuck at this specific function:
/**
* #return an iterator for the Avl Tree. The returned iterator iterates over the tree nodes.
* in an ascending order, and does NOT implement the remove() method.
*/
public Iterator<Integer> iterator(){
List myList=new ArrayList<>();
Node counter=root;
Node counter1=root.getChildernLeft();
if(counter1==null){
myList.add(counter1);
}
Node counter1=root.getChildernLeft();
}
I added my two classes:
full code, Node class:
public class Node {
private Node parent;
private Node childernRight;
private Node childernLeft;
private int data;
private int height;
/**
* constractor
*/
public Node(int data, Node childernLeft, Node childernRight) {
this.data = data;
this.childernLeft = childernLeft;
this.childernRight = childernRight;
this.childernRight.setParent(this);
this.childernLeft.setParent(this);
}
public Node(int data) {
this.data = data;
}
public Node getParent() {
return parent;
}
public Node getChildernRight() {
return childernRight;
}
public Node getChildernLeft() {
return childernLeft;
}
public void setParent(Node parent) {
this.parent = parent;
}
public void setChildernRight(Node childernRight) {
this.childernRight = childernRight;
this.childernRight.setParent(this);
}
public void setChildernLeft(Node childernLeft) {
this.childernLeft = childernLeft;
this.childernLeft.setParent(this);
}
public int getData() {
return data;
}
public String toString() {
if (this.childernLeft != null && this.getChildernRight() != null) {
return childernLeft.toString() + "," + this.data + "," + childernRight.toString();
} else if (this.childernLeft != null && this.getChildernRight() == null) {
return childernLeft.toString() + "," + this.data;
} else if (this.childernLeft == null && this.getChildernRight() != null) {
return this.data + "," + childernRight.toString();
} else {
return this.data + "";
}
}
public int balanceFactor() {
int balanceFactor = childernRight.height - childernLeft.height;
return balanceFactor;
}
public boolean hasChildrenRight() {
if (this.childernRight != null) {
return true;
}
else{
return false;
}
}
public boolean hasChildrenLeft() {
if (this.childernLeft != null) {
return true;
}
else{
return false;
}
}
/**
* if we have many children in the tree
*/
public void addNode(Node val){
if(hasChildrenRight()&&this.data>val.data){
this.setChildernRight(val);
}
if(!hasChildrenLeft()&&this.data<val.data){
this.setChildernLeft(val);
}
if(!hasChildrenLeft()&&!hasChildrenRight()){
if(this.data>val.data){
setChildernLeft(val);
}
else{
setChildernRight(val);
}
}
if(val.data>this.data){
childernRight.addNode(val);
}
else{
childernLeft.addNode(val);
}
}
}
full code for AvlTree:`
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
public class AvlTree {
private Node root;
private int size;
/**
* default constructor.
*/
public AvlTree() {
this.root = null;
this.size = 0;
}
/**
* A constructor that builds a new AVL tree containing all unique values in the input
* array
*
* #param data the values to add to tree
*/
public AvlTree(int[] data) {
for (int i = 0; i < data.length; i++) {
add(data[i]);
}
}
/**
* A copy constructor that creates a deep copy of the given oop.ex4.data_structures.AvlTree. The new tree
* contains all the values of the given tree, but not necessarily in the same structure.
*
* #param avlTree an AVL tree.
*/
public AvlTree(AvlTree avlTree) {
}
/**
* Add a new node with the given key to the tree.
*
* #param newValue the value of the new node to add.
* #return true if the value to add is not already in the tree and it was successfully added,
* false otherwise.
*/
public boolean add(int newValue) {
if (root == null) {
root = new Node(newValue);
size++;
return true;
}
Node current = root;
Node parent = null;
while (current != null) {
if (current.getData() == newValue) {
return false;
}
parent = current;
if (newValue < current.getData()) {
current = current.getChildernLeft();
} else {
current = current.getChildernRight();
}
}
size++;
// when we here the new NODE Need to be chiled of Node hashmor in parent.
// addHelper is adding the new Node.2
// addHelper(newNodeToAdd, current);
return true;
}
private void addHelper(Node newNodeToAdd, Node current) {
// if (newNodeToAdd.getData() > current.getData()) {
// if (current.getChildernRight() == null) {
// current.setChildernRight(newNodeToAdd);
// } else {
// addHelper(newNodeToAdd, current.getChildernRight());
// }
// } else {
// if (current.getChildernLeft() == null) {
// current.setChildernLeft(newNodeToAdd);
// } else {
// addHelper(newNodeToAdd, current.getChildernLeft());
// }
// }
}
/**
* Check whether the tree contains the given input value.
*
* #param searchVal the value to search for.
* #return the depth of the node (0 for the root) with the given value if it was found in the tree, −1 otherwise.
*/
public int contains(int searchVal) {
Node current = root;
int depth = 0;
while (current != null) {
if (current.getData() == searchVal) {
return depth;
}
depth++;
if (searchVal < current.getData()) {
current = current.getChildernLeft();
} else {
current = current.getChildernRight();
}
}
return -1;
}
/**
* Removes the node with the given value from the tree, if it exists.
*
* #param toDelete the value to remove from the tree.
* #return true if the given value was found and deleted, false otherwise.
*/
public boolean delete(int toDelete) {
size -= 1;
return true;
}
/**
* #return the number of nodes in the tree.
*/
public int size() {
return size;
}
/**
* #return an iterator for the Avl Tree. The returned iterator iterates over the tree nodes.
* in an ascending order, and does NOT implement the remove() method.
*/
public Iterator<Integer> iterator(){
List myList=new ArrayList<>();
Node counter=root;
Node counter1=root.getChildernLeft();
if(counter1==null){
myList.add(counter1);
}
Node counter1=root.getChildernLeft();
}
/**
* Calculates the minimum number of nodes in an AVL tree of height h
*
* #param h the height of the tree (a non−negative number) in question.
* #return the minimum number of nodes in an AVL tree of the given height.
*/
public static int findMinNodes(int h) {
// I SOVLE THIS WITH ROCKISA
int counterMin = 0;
if (h == 0) {
return counterMin = 1;
}
if (h == 1) {
return counterMin = 2;
}
return (findMinNodes(h - 1) + findMinNodes(h - 2) + 1);
}
/**
* Calculates the maximum number of nodes in an AVL tree of height h.
*
* #param h the height of the tree (a non−negative number) in question.
* #return the maximum number of nodes in an AVL tree of the given height.
*/
public static int findMaxNodes(int h) {
int counterMax = 0;
for (int i = 0; i < h; i++) {
counterMax += Math.pow(h, i);
}
return counterMax;
}
/**
* #return
*/
public String toString() {
if (root == null) {
return "";
}
return root.toString();
}
//THIS IS OK
public void RotationRr(Node valRotation) {
if (valRotation == root) {
Node keepRootChild = root.getChildernRight();
root.setChildernRight(null);
}
Node parent1 = valRotation.getParent();
Node keepRightChild = valRotation.getChildernRight();///4
valRotation.setChildernRight(null);
keepRightChild.setParent(parent1);
if (!keepRightChild.hasChildrenLeft()) {
keepRightChild.setChildernLeft(valRotation);
valRotation.setParent(keepRightChild);
} else {
keepRightChild.getChildernLeft().addNode(valRotation);
}
}
public void RotationLr(Node valRotation) {
RotationLl(valRotation);
}
/**
* ........CHECK.....!!!!TODO
*
* #param valRotation
*/
public void RotationLl(Node valRotation) {
Node parent2 = valRotation.getParent();
Node keepLeftChild = valRotation.getChildernLeft();
valRotation.setChildernLeft(null);
keepLeftChild.setParent(parent2);
if (!keepLeftChild.hasChildrenRight()) {
keepLeftChild.setParent(keepLeftChild);
} else {
keepLeftChild.getChildernRight().addNode(valRotation);
}
}
public void RotationRl(Node valRotation) {
RotationRr(valRotation);
}
public static void main(String[] args) {
AvlTree avlTree = new AvlTree();
avlTree.add(7);
avlTree.add(2);
System.out.println(avlTree.contains(2));
// System.out.println(avlTree.contains(5));
avlTree = new AvlTree();
avlTree.add(2);
avlTree.add(7);
System.out.println(avlTree.contains(2));
// System.out.println(avlTree);
}
}
`
You can implement a iterator using stack
public Iterator<V> iterator() {
return new Itr();
}
private class Itr<V> implements Iterator<V> {
TreeNode<V> localNode = (TreeNode<V>) root;
Stack<TreeNode<V>> stack;
public Itr() {
stack = new ArrayStack<TreeNode<V>>();
while (localNode != null) {
stack.push(localNode);
localNode = localNode.getLeftChield();
}
}
public boolean hasNext() {
return !stack.empty();
}
public V next() {
TreeNode<V> node = stack.pop();
V v = node.getValue();
if (node.getRightChield() != null) {
node = node.getRightChield();
while (node != null) {
stack.push(node);
node = node.getLeftChield();
}
}
return v;
}
public void remove() {
throw new UnsupportedOperationException();
}
}

LinkedLlist with tree in java

I am trying to create tree linked list in java and print Tree by levels of balls in metric spaces and I am unsuccessful.
create class ball:
public class Ball {
private double Point;
private double Radius;
public Ball(double Point, double Radius) {
this.Point = Point;
this.Radius = Radius;
}
public double getPoint() {
return Point;
}
public double getRadius() {
return Radius;
}
public void setPoint(double p)
{
this.Point=p;
}
public void setRadius(double r)
{
this.Radius=r;
}
public String toString(Ball b)
{
return b.Point+ " " + b.Radius;
}
}
and create class TreeNode
import java.util.LinkedList;
import java.util.List;
import java.util.ListIterator;
public class TreeNode<T> {
T data;
TreeNode<T> parent;
LinkedList<TreeNode<T>> children;
TreeNode next;
public TreeNode(T data ) {
this.data = data;
this.children = new LinkedList<TreeNode<T>>();
this.parent = null;
}
public TreeNode(T data , TreeNode<T> parent)
{
this.data=data;
this.parent=parent;
this.children = new LinkedList<TreeNode<T>>();
}
public TreeNode<T> addChild(T child)
{
TreeNode<T> childNode = new TreeNode<T>(child);
childNode.parent = this;
this.children.add(childNode);
return childNode;
}
public void setNext(TreeNode e)
{
this.next=e;
}
public TreeNode getNext()
{
return this.next;
}
public TreeNode <T> Insert(TreeNode<T> pos, T x)
{
TreeNode <T> tmp = new TreeNode <T>(x);
if(pos == null)
{
tmp.setNext(this.parent);
this.parent= tmp;
}
else{
tmp.setNext(pos.getNext());
}
return tmp;
}
public TreeNode<T> getParent() {
return parent;
}
public T getData() {
return data;
}
public LinkedList<TreeNode<T>> getChild ()
{
return children;
}
public void setData(T data1)
{
this.data=data1;
}
public void setParent(TreeNode<T> getParent)
{
this.parent=parent;
}
public String toString()
{
return this.data.toString() ;
}
}
In addition create class cover tree levels
my problem is insert element to tree
public class CoverTreeLevels {
static final int LEVELS = 25;
public static Data d;
public static void Insert(TreeNode node, TreeNode newNode)
{
newNode.parent=node.parent;
node.parent=newNode.parent;
}
public static void buildTree(double [][] data)
{
double rootRadius =d.Find_Max_Radiues(d.data);
Ball rootBall = new Ball(data[0][0], rootRadius);
TreeNode root = new TreeNode<Ball>(rootBall);
TreeNode last = root;
for (double i = 1, lastRadius = rootRadius / 2; i < LEVELS - 1; i++, lastRadius /= 2) {
Ball ball = new Ball( data[0][0] , lastRadius);
last = last.addChild(ball);
for (int j = 1; j < data.length; j++) {
TreeNode<Ball> n = last;
while (true)
{
if(d.dist(j, 0)> lastRadius)
{
Ball newBall = new Ball(data[j][0], lastRadius);
n.addChild(newBall) ;
}
n.getParent();
}
}
}
}
and class Data which includes data in metric spaces.
Am I headed in the right direction?
For one, it looks like you have some issues with access modifiers in this code.
Here, you're referencing private properties of these objects without using the getters/setters you specified. This will be a compiler error.
Second, your insert method seems to be setting the node.parent to itself.
public static void Insert(TreeNode node, TreeNode newNode)
{
newNode.parent=node.parent; // new node's parent is being set to current node's parent.
node.parent=newNode.parent; // current node's parent being set to newNode's parent, which you just assigned to node.parent above
}
To insert properly, you'd need to insert the newNode itself into the equation:
public static void Insert(TreeNode node, TreeNode newNode)
{
if ( node != null && newNode != null) {
TreeNode temp;
temp = node.getParent(); // get the current node's parent
node.setParent(newNode); // set the new parent of current node to newNode
newNode.setParent(temp); // set the new node's parent to current node's old parent
}
}
Now you should have a properly functioning insert.

CircularlinkedList generics

I am experiencing a problem with generics in a CircularLinkedList. I have my CircularLinkedList class, a Node class and a Person class.
The Node's should contain persons and the CircularLinkedList should contain those nodes. The problem is, that when i try to create my CircularLinkedList in my Test class, i get an error saying:
Bound mismatch: The type Node<Person> is not a valid substitute for
the bounded parameter <E extends Comparable<? super E>> of the type
CircularLinkedList<E>
Can you take a look at my generics?
CircularLinkedList.java
package cirkulærliste;
import java.util.Random;
public class CircularLinkedList<E extends Comparable<? super E>> {
private Node<E> next;
private Node<E> start;
private int size = 0;
public CircularLinkedList() {
setNext(null);
}
/**
* tilføjer personer
* #param p
*/
public void addPerson(E e) {
Node<E> newNode = new Node<E>(e, null);
Node<E> tempNext = next;
if(next == null){
next = newNode;
next.setNext(next);
} else if(size > 1){
}
}
/**
* udskriver personerne i den rækkefølge de står i listen
*/
public void print() {
Node<E> tempNode = start;
while (!tempNode.getNext().equals(start)) {
System.out.println(tempNode);
tempNode = tempNode.getNext();
}
System.out.println(tempNode);
}
/**
* en tilfældig person i den cirkulæreliste vælges som start i listen
*/
public void randomStart() {
int size = 1;
Node<E> tempNode = next.getNext();
while (!tempNode.getNext().equals(next.getNext())) {
tempNode = tempNode.getNext();
size++;
}
Random randomizer = new Random();
int chosen = randomizer.nextInt(size);
for (int i = 0; i <= chosen; i++) {
tempNode = tempNode.getNext();
}
start = tempNode;
}
/**
* fjerner den person fra listen der ligger count pladser fra start i listen. Personen der fjernes returneres.
* #param count
*/
public Node<E> remove(int count) {
Node<E> tempNode2;
for (int i = 1; i < 5; i++) {
next = next.getNext();
}
tempNode2 = next.getNext();
next.setNext(next.getNext().getNext());
tempNode2.setNext(null);
return tempNode2;
}
public void setNext(Node<E> next) {
this.next = next;
}
public Node<E> getNext() {
return next;
}
public void setStart(Node<E> start) {
this.start = start;
}
public Node<E> getStart() {
return start;
}
}
Node.java
package cirkulærliste;
public class Node<E> {
private E element;
private Node<E> next;
public Node(){
element = null;
next = null;
}
public Node(E element, Node<E> next){
this.setElement(element);
this.next = next;
}
public E getElement() {
return element;
}
public void setElement(E element) {
this.element = element;
}
public Node<E> getNext() {
return next;
}
public void setNext(Node<E> newNode) {
this.next = newNode;
}
public String toString(){
return "" + element;
}
}
Person.java
package cirkulærliste;
public class Person implements Comparable<Person> {
private String name;
private int number;
public Person(String name, int number){
this.setName(name);
this.setNumber(number);
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String toString(){
return "Name: " + name + " - " + "Number: " + number;
}
public int getNumber() {
return number;
}
public void setNumber(int number) {
this.number = number;
}
#Override
public int compareTo(Person o) {
// TODO Auto-generated method stub
return 0;
}
}
Test.java
public class Test {
public static void main(String[] args) {
CircularLinkedList<Person> list = new CircularLinkedList<Person>();
Node<Person> n1 = new Node<Person>();
n1.setElement(new Person("Thomas", 1));
list.addPerson(n1); // Compile error occurs here
}
}
It sounds like you're writing
CircularLinkedList<Node<Person>>
in your Test class; but you actually need to be writing
CircularLinkedList<Person>
Update for updated question: You also need to change this:
Node<Person> n1 = new Node<Person>();
n1.setElement(new Person("Thomas", 1));
list.addPerson(n1); // Compile error occurs here
to this:
list.addPerson(new Person("Thomas", 1));
In general, code that uses CircularLinkedList shouldn't refer to Node; CircularLinkedList uses Node internally, but users of the class don't need to worry about that.
Also, it's kind of odd that your generic CircularLinkedList class has a method named addPerson. Surely it should be called addElement, or just add?
Putting your code into an IDE gives me an error here:
Node<Person> n1 = new Node<Person>();
n1.setElement(new Person("Thomas", 1));
list.addPerson(n1);
A method addPerson(E e) on a collection of type CircularLinkedList<Person> expects a Person instance as a parameter. Your implementation of addPerson even creates a new Node instance (as it should), so there's no need to do it in calling code.
This compiles fine:
list.addPerson(new Person("Thomas", 1));

Categories

Resources