Summing elements of binary tree in Java - java

I'm trying to sum the elements of a binary tree with a recursive and an iterative method. While the recursive one works finde, the iterative gives me an exception.
import java.util.Queue;
public class BinTree {
public BinNode root;
public boolean insertNode(BinNode bn) {
BinNode child=null, parent=null;
// Knoten suchen, nach welchem eingefuegt wird
child = root;
while( child != null) {
parent = child;
if (bn.element == child.element) return false;
else if (bn.element < child.element) child = child.left;
else child = child.right;
}
// Baum leer?
if (parent==null) root = bn;
// Einfuegen nach parent, links
else if (bn.element < parent.element) parent.left = bn;
// Einfuegen nach parent, rechts
else parent.right = bn;
return true;
}
public BinNode findNode(int value) {
BinNode n = root;
while (n != null) {
if (value == n.element) { return n; }
else if (value < n.element) { n = n.left; }
else { n = n.right; }
}
return null;
}
public String toString() {
return root.toString();
}
//Max des Gesamtbaumes
public int max(){
if(root==null){
return 0;
}
else {
return root.max();
}
}
//(Iterativ)
public int max2(){
//The line that throws out the exception
Queue q = new LinkedList();
int sum = 0;
if(root!=null){
q.add(root);
}
while(!q.isEmpty()){
BinNode node = (BinNode) q.remove();
if(node.left == null && node.right == null){
sum = sum + node.element;
}
else{
if(node.left != null){
q.add(node.left);
}
}
if(node.right != null){
q.add(node.right);
}
}
return sum;
}
}
The Queue q = new LinkedList(); in the max2-Method is giving me the Exception:
Exception in thread "main" java.lang.RuntimeException: Uncompilable source code - incompatible types: javaapplication34.LinkedList cannot be converted to java.util.Queue
Could anyone help here? Give me a kickstart or a little explanation? I'm very unsure what's the issue in detail.
I didn't add every class here, since most of them are common. But if needed I'll add them.

It appears that you have defined a class called LinkedList in the same package, and it doesn't implement Queue.
If you want to use a java.util.LinkedList, you should either import or use the entire qualified name.

We don't know the implementation of you special LinkedList class (only that it does not implement the java.lang.Queue interface), but it may work already if you just say:
LinkedList q = new LinkedList();
(I assume that it is an assignment and that you have to use this special LinkedList for the task)

Related

Illegal start of expression with <> [duplicate]

This question already has answers here:
What is the point of the diamond operator (<>) in Java?
(7 answers)
Closed 5 years ago.
I keep on getting this whenever I run my code with -Xlint:
Tester.java:11: error: illegal start of type
DoubleThreadedBST<> BST = new DoubleThreadedBST()<>;
^
Tester.java:11: error: illegal start of expression
DoubleThreadedBST<> BST = new DoubleThreadedBST()<>;
^
Tester.java:11: error: illegal start of expression
DoubleThreadedBST<> BST = new DoubleThreadedBST()<>;
the code is meant to make a double threaded binary search treee. I'd like to actually test my code but I keep on getting these errors
my code:
DoubleThreadedBST
Code is selfexplanitory(also has comments)
public class DoubleThreadedBST<T extends Comparable<? super T>>
{
private DTNode<T> root; // the root node of the tree
public static boolean dLeft;
public static boolean dRight;
/*
TODO: You must complete each of the methods in this class to create
your own double threaded BST. You may add any additional methods
or data fields which you might need to accomplish your task. You
must NOT change the signatures of any methods given to you with this
class.
*/
public DoubleThreadedBST()
{
root = null;
}
public DoubleThreadedBST(DoubleThreadedBST<T> other)
{
root = other.getRoot();
}
public DoubleThreadedBST<T> clone()
{
DoubleThreadedBST<T> other = new DoubleThreadedBST<T>();
other.setRoot(this.root);
return other;
}
public DTNode<T> getRoot()
{
return root;
}
public void setRoot(DTNode<T> r){
root = r;
}
public boolean insert(T element){
DTNode<T> newNode = new DTNode<T>(element);
if(root != null){
if(contains(element) == false){
if(root.hasLeftT() != true){
root.setLeft(newNode);
root.setHasLeftT(true);
root.setLeftBit(1);
newNode.setRight(root);
newNode.setHasRightT(true);
newNode.setRightBit(0);
return true;
}else if (root.hasRightT() != true){
root.setRight(newNode);
root.setHasRightT(true);
root.setRightBit(1);
newNode.setLeft(root);
newNode.setHasLeftT(true);
newNode.setLeftBit(0);
return true;
}else{
DTNode<T> trav = root.getLeft();
while(true){
if(trav.getData().compareTo(newNode.getData()) == 1){
if(trav.getLeftBit() == 0){
newNode.setLeft (trav.getLeft());
trav.setLeft(newNode);
newNode.setLeftBit (trav.getLeftBit());
trav.setLeftBit(1);
newNode.setRight(trav);
break;
}else{
trav = trav.getLeft();
}
}else{
if(trav.getRightBit() == 0){
newNode.setRight(trav.getRight());
trav.setRight(newNode);
newNode.setRightBit(trav.getRightBit());
trav.setRightBit(1);
newNode.setLeft(trav);
break;
}else{
trav = trav.getRight();
}
}
}
}
}else{
return false;
}
}else{
root = newNode;
root.setLeft(null);
root.setRight(null);
root.setHasLeftT(false);
root.setHasRightT(false);
return true;
}
/*
The element passed in as a parameter should be
inserted into this tree. Duplicates are not allowed.
Left and right threads in the corresponding branch
must be updated accordingly, as necessary.
If the insert was successfull, the method should
return true. If the operation was unsuccessfull,
the method should return false.
NB: Do not throw an exception.
*/
return true;
}
/*
public boolean delete(T element){
if(contains(element){
DTNode<T> trav = root;
while (trav.getLeft()!= null){
trav = trav.getLeft();
}
while(trav != null){
if(trav.getRight().getData() == element){
DTNode<T> temp = trav.getRight();
trav.setRight(keeper.getRight());
while (temp 1= null){
}
}
if(trav.hasRightT()){
trav = trav.getRight();
}else{
trav = trav.getLeft();
}
}
}
*/
/*
The element passed in as a parameter should be
deleted from this tree. If the delete was successfull,
the method should return true. If the operation was
unsuccessfull, the method should return false. Eg, if
the requested element is not found, return false.
You have to implement the mirror case of delete by merging
as discussed in the textbook. That is, for a deleted node,
its right child should replace it in the tree and not its
left child as in the textbook examples. Relevant left and
right threads must be updated accordingly.
NB: Do not throw an exception.
return false;
}
*/
public boolean contains(T element){
if(root != null){
DTNode<T> trav = root;
while (trav.getLeft()!= null){
trav = trav.getLeft();
}
while(trav != null){
if(trav.getData() == element){
return true;
}
if(trav.hasRightT()){
trav = trav.getRight();
}else{
trav = trav.getLeft();
}
}
}
return false;
}
public String inorderAscending(){
String tree = "";
if(root != null){
DTNode<T> trav = root;
while (trav.getLeft()!= null){
trav = trav.getLeft();
}
while(trav != null){
tree += trav.getData();
if(trav.getRight() != null){
tree += ",";
}
if(trav.hasRightT()){
trav = trav.getRight();
}else{
trav = trav.getLeft();
}
}
}
/*
This method must return a string representation
of the elements in the tree inorder, left to right.
This function must not be recursive. Instead, right
threads must be utilised to perform a depth-first
inorder traversal.
If the tree looks like:
B
/ \
A D
/ \
C E
Then the following string must be returned:
A,B,C,D,E
Note that there are no spaces in the string, and
the elements are comma-separated.
*/
return tree;
}
public String inorderDescending(){
String tree = "";
if(root != null){
DTNode<T> trav = root;
while (trav.getRight()!= null){
trav = trav.getRight();
}
while(trav != null){
tree += trav.getData();
if(trav.getLeft() != null){
tree += ",";
}
if(trav.hasLeftT()){
trav = trav.getLeft();
}else{
trav = trav.getRight();
}
}
}
/*
This method must return a string representation
of the elements in the tree inorder, right to left.
This function must not be recursive. Instead, left
threads must be utilised to perform a depth-first
inorder traversal.
If the tree looks like:
B
/ \
A D
/ \
C E
Then the following string must be returned:
E,D,C,B,A
Note that there are no spaces in the string, and the elements are comma-separated.
*/
return tree;
}
public int countRightThreads(){
int count = 0;
if(root != null){
DTNode<T> trav = root;
while (trav.getRight() != null){
trav = trav.getRight();
count ++;
}
while(trav != null){
if(trav.hasLeftT()){
trav = trav.getLeft();
}else{
count++;
trav = trav.getRight();
}
}
}
/*
This method should return the total number of right threads
in the tree.
*/
return count;
}
public int countLeftThreads(){
int count = 0;
if(root != null){
DTNode<T> trav = root;
while (trav.getLeft()!= null){
trav = trav.getLeft();
count++;
}
while(trav != null){
if(trav.hasLeftT()){
trav = trav.getLeft();
count ++;
}else{
trav = trav.getRight();
}
}
}
/*
This method should return the total number of left threads
in the tree.
*/
return count;
}
public int getNumberOfNodes()
{
int count = 0;
if(root != null){
DTNode<T> trav = root;
while (trav.getLeft()!= null){
trav = trav.getLeft();
count++;
}
while(trav != null){
if(trav.hasLeftT()){
trav = trav.getLeft();
count ++;
}else{
trav = trav.getRight();
count++;
}
}
}
/*
This method should count and return the number of nodes
currently in the tree.
*/
return count;
}
public int getHeight()
{
/*
This method should return the height of the tree. The height
of an empty tree is 0; the height of a tree with nothing but
the root is 1.
*/
return 0;
}
}
Tester
Just for testing
public class Tester
{
public static void main(String[] args) throws Exception
{
/*
TODO: Write your code to test your implementation here.
This file will be overwritten for marking purposes
*/
DoubleThreadedBST<> BST = new DoubleThreadedBST()<>;
BST.insert(1);
BST.insert(2);
BST.insert(3);
BST.insert(5);
BST.insert(4);
System.out.println(BST.inorderAscending());
System.out.println(BST.inorderDescending());
}
}
DTNode
Has a left and a right while my ...Bits show whether they left and right are pointing to an in order parent or a child node.
public class DTNode<T extends Comparable<? super T>>
{
/*
TODO: You must implement a node class which would be appropriate to use with your trees.
Methods and variables can be added.
Names of the given variables must not be altered.
*/
//setters
public DTNode(){
}
public DTNode(T elem){
data = elem;
}
public void setLeft(DTNode<T> n){
left = n;
}
public void setRight(DTNode<T> n){
right = n;
}
public void setData(T elem){
data = elem;
}
public void setHasLeftT(boolean t){
hasLeftThread = t;
}
public void setHasRightT(boolean t){
hasRightThread = t;
}
public void setLeftBit(int b){
leftBit = b;
}
public void setRightBit(int b){
rightBit= b;
}
//getters
public DTNode<T> getLeft(){
return left;
}
public DTNode<T> getRight(){
return right;
}
public T getData(){
return data;
}
public boolean hasLeftT(){
return hasLeftThread;
}
public boolean hasRightT(){
return hasRightThread;
}
public int getLeftBit(){
return leftBit;
}
public int getRightBit(){
return rightBit;
}
protected T data;
protected DTNode<T> left, right; // left child and right child
protected boolean hasLeftThread, hasRightThread; // flags that indicate whether the left and the right pointers are threads
protected int leftBit, rightBit;
}
Reference declaration doesnt accept diamond operator, which means you have to send a generic argument. Repleace this:
DoubleThreadedBST<> BST = new DoubleThreadedBST()<>;
with:
DoubleThreadedBST<Integer> BST = new DoubleThreadedBST<>();

Binary-Search Tree

Here is my code to find position of a certain element. And I am using Binary tree to store my Dictionary I want to know why it shows warning for Comparable-type. I have to use this in my project where element is a string type.
public int get(Comparable element){
return getPosition(element,root);
}
private int getPosition(Comparable element, TreeNode root){
int count = 0;
if (root == null){
return -1;
}else{
Stack t = new Stack();
t.push(root);
while(!t.empty()){
TreeNode n = (TreeNode)t.pop();
if(element.compareTo(n.value)==0){
return count;
}else{
if(n.getLeftTree()!=null){
t.push(n.getLeftTree());
count++;
}
if (n.getRightTree()!= null){
t.push(n.getRightTree());
count++;
}
}
}
return -1;
}
}
The java generic typing parameters are missing <...>.
public int get(Comparable<?> element){
return getPosition(element, root);
}
private int getPosition(Comparable<?> element, TreeNode root) {
int count = 0;
if (root == null) {
return -1;
} else {
Stack<TreeNde> t = new Stack<>();
t.push(root);
while (!t.empty()) {
TreeNode n = t.pop();
if (element.compareTo(n.value) == 0) {
return count;
} else {
if (n.getLeftTree() != null) {
t.push(n.getLeftTree());
count++;
}
if (n.getRightTree() != null) {
t.push(n.getRightTree());
count++;
}
}
}
}
return -1;
}
However the algorithm seems not to be counting the leftish part of the tree upto the found element. However if position is not the index in the sorted elements, that might be okay. (I did not check the correctness, as there is no early < check.) If this was a home work assignment, "non-recursive with stack," rework a recursive version. Probably two nested loops, and a comparison on -1 and +1.

implementing binary search tree insert

I'm trying to write code for a binary search tree, the first method I'm working on is the add (insert) method. The root seems to insert properly, but I'm getting null pointer exception when adding the second node. I'll indicate the exact problem spot in my code with comments.
If you can see how to fix the bugs, or let me know if my overall logic is flawed it would be incredibly helpful.-- I will mention that this is for school, so I'm not looking to make a really impressive model...most of my layout choices simply reflect the way we've been working in class. Also, method names were selected by the teacher and should stay the same. Feel free to edit the formatting, had a little trouble.
BINARY TREE CLASS
public class BinarySearchTree
{
private static Node root;
public BinarySearchTree()
{
root = null;
}
public static void Add (Node newNode)
{
Node k = root;
if (root == null)//-----------------IF TREE IS EMPTY -----------------
{
root = newNode;
}
else // -------TREE IS NOT EMPTY --------
{
if (newNode.value > k.value) //-------NEW NODE IS LARGER THAN ROOT---------
{
boolean searching = true;
while(searching) // SEARCH UNTIL K HAS A LARGER VALUE
{ //***CODE FAILS HERE****
if(k.value > newNode.value || k == null)
{
searching = false;
}
else {k = k.rightChild; }
}
if ( k == null) { k = newNode;}
else if (k.leftChild == null){ k.leftChild = newNode;}
else
{
Node temp = k.leftChild;
k.leftChild = newNode;
newNode = k.leftChild;
if(temp.value > newNode.value )
{
newNode.rightChild = temp;
}
else
{
newNode.leftChild = temp;
}
}
}
if (newNode.value < k.value) //-----IF NEW NODE IS SMALLER THAN ROOT---
{
boolean searching = true;
while(searching) // ----SEARCH UNTIL K HAS SMALLER VALUE
{// **** CODE WILL PROBABLY FAIL HERE TOO ***
if(k.value < newNode.value || k == null) {searching = false;}
else {k = k.leftChild;}
}
if ( k == null) { k = newNode;}
else if (k.rightChild == null){ k.rightChild = newNode;}
else
{
Node temp = k.rightChild;
k.rightChild = newNode;
newNode = k.rightChild;
if(temp.value > newNode.value )
{
newNode.rightChild = temp;
}
else
{
newNode.leftChild = temp;
}
}
}
}} // sorry having formatting issues
}
NODE CLASS
public class Node
{
int value;
Node leftChild;
Node rightChild;
public Node (int VALUE)
{
value = VALUE;
}
}
TEST APPLICATION
public class TestIT
{
public static void main(String[] args)
{
BinarySearchTree tree1 = new BinarySearchTree();
Node five = new Node(5);
Node six = new Node(6);
tree1.Add(five);
tree1.Add(six);
System.out.println("five value: " + five.value);
System.out.println("five right: " + five.rightChild.value);
}
}
The conditional statement is checked from left to right, so you need to check whether k is null before you check whether k.value > newNode.value because if k is null, then it doesn't have a value.

Linked List Array

I have this school assignment that I'm a little confused about.
Here's what it's saying:
"Write a program that uses the technique of 'chaining' for hashing.
The program will read in the length of an array which will contain the reference to each
linked list that will be generated. Furthermore, all values that are to be stored, is read.
The program shall have a separate function for hashing where the index exists. When the program have generated the linked lists, the theoretical 'load factor' is to be calculated and printed out. The whole array should be easily printed out."
The thing that I'm confused about, is the part about the program will read in the length of an array which will contain the reference to each linked list that will be generated. Is it possible to generate multiple linked lists? In that case, how do you do that?
This is the classes I'm told to use:
public class EnkelLenke {
private Node head = null;
private int numOfElements = 0;
public int getNum()
{
return numOfElements;
}
public Node getHead()
{
return head;
}
public void insertInFront(double value)
{
head = new Node (value, head);
++numOfElements;
}
public void insertInBack(double value)
{
if (head != null)
{
Node this = head;
while (this.next != null)
this = this.next;
this.next = new Node(value, null);
}
else
head = new Node(value, null);
++numOfElements;
}
public Node remove(Node n)
{
Node last = null;
Node this = head;
while (this != null && this != n)
{
last = this;
this = this.next;
}
if (this != null)
{
if (last != null)
last.next = this.next;
else
head = this.next;
this.next = null;
--numOfElements;
return this;
}
else
return null;
}
public Node findNr(int nr)
{
Node this = head;
if (nr < numOfElements)
{
for (int i = 0; i < nr; i++)
this = this.next;
return this;
}
else
return null;
}
public void deleteAll()
{
head = null;
numOfElements = 0;
}
public String printAllElements() {
String streng = new String();
Node this = head;
int i = 1;
while(this != null)
{
streng = streng + this.element + " ";
this = this.findNext();
i++;
if(i > 5)
{
i = 1;
streng = streng + "\n";
}
}
return streng;
}
public double getValueWithGivenNode (Node n)
{
Node this = head;
while (this != null && this != n)
{
this = this.next;
}
if (this == n)
return this.element;
else
return (Double) null;
}
}
public class Node {
double element;
Node next;
public Node(double e, Node n)
{
element = e;
next = n;
}
public double findElement()
{
return element;
}
public Node findNext()
{
return next;
}
}
Your data structure will look something like this (where "LL" is a linked list):
i | a[i]
-------------------------------
0 | LL[obj1 -> obj5 -> obj3]
1 | LL[obj2]
2 | LL[]
... | ...
N-1 | LL[obj4 -> obj6]
At each array index, you have a linked list of objects which hash to that index.
Is it possible to generate multiple linked lists? In that case, how do you do that?
Yes. Create your array, and initialize each element to a new linked list.
EnkelLenke[] a = new EnkelLenke[N];
for ( int i = 0; i < N; i++ ) {
a[i] = new EnkelLenke();
}

circular single linkedList

I've done some exercises in Java and now I'm stuck at such a problem - my list works incorrectly. I am sure that remove works incorrectly and maybe you can help me (with advice or code) to implement a circular singly linked list in a correct way. I am not sure whether other functions work properly, but I've tried to do my best.
Here is my code:
import java.util.*;
public class Node {
private Object value;
private Object nextValue;
private Node next;
public Node(int data) {
this.value = data;
this.next = null;
}
public Object getValue() {
return this.value;
}
public Node nextItem() {
return this.next;
}
public void setNextItem(Node nextItem) {
this.next = (Node) nextItem;
this.next.setValue(nextItem.getValue());
}
public void setValue(Object arg0) {
this.value = arg0;
}
}
-------------------------------------------------------------------
import java.util.*;
public class CircularList {
private Object[] array;
private int arrSize;
private int index;
private Node head;
private Node tail;
public CircularList() {
head = null;
tail = null;
}
public boolean add(Node item) {
if (item == null) {
throw new NullPointerException("the item is null!!!");
}
if (head == null) {
head = item;
head.setNextItem(head);
arrSize++;
return true;
}
Node cur = head;
while(cur.nextItem() != head) {
if(cur.getValue() == item.getValue()) {
throw new IllegalArgumentException("the element already " +
"exists!");
}
cur = cur.nextItem();
}
head.setNextItem(item);
item.setNextItem(head);
arrSize++;
return true;
}
public Node getFirst() {
return head;
}
public void insertAfter(Node item, Node nextItem) {
if ((item == null) || (nextItem == null)) {
throw new NullPointerException("the item is nul!!!");
} else if (this.contains(nextItem) == true) {
throw new IllegalArgumentException("the item already exists!");
}
Node cur = head;
while(cur.nextItem() != head) {
if(cur.getValue() == item.getValue()) {
nextItem.setNextItem(item.nextItem());
item.setNextItem(nextItem);
} else {
cur = cur.nextItem();
}
}
}
public boolean remove(Node item) {
if(item == head) {
Node cur = head;
for(int i = 0; i < arrSize-1; i++) {
cur = cur.nextItem();
}
head = head.nextItem();
for(int i = 0; i < arrSize; i++) {
cur = cur.nextItem();
}
arrSize--;
return true;
}
Node cur = head;
int counter = 0;
while(cur.nextItem() != head) {
if(cur == item) {
item = null;
cur = cur.nextItem();
while(cur.nextItem() != head) {
cur.setNextItem(cur.nextItem().nextItem());
}
return true;
}
cur = cur.nextItem();
}
return false;
}
public int size() {
return arrSize;
}
public boolean contains(Object o) {
if ((o == null) && (arrSize == 0)) {
return false;
}
Node cur = head;
while(cur.nextItem() != head) {
if(cur.getValue() == o) {
return true;
}
cur = cur.nextItem();
}
return false;
}
}
Many of these algorithms could be simpler.
Example:
public boolean remove(Node item) {
Node current = head;
for(int i = 0; i < size; i++) {
if (current.getNext() == item) {
current.next = current.getNext().getNext();
size --;
return true;
}
current = current.getNext()
}
return false;
}
There are a variety of issues here beyond the list. You seem to be comparing your nodes with ==. This code will output 'no match'.
Node n1 = new Node(5);
Node n2 = new Node(5);
if (n1 == n2)
System.out.println("objects match");
else
System.out.println("no match");
In add(), it looks like you can only ever have two items in the list, so
head.setNextItem(item);
item.setNextItem(head);
should be this:
cur.setNextItem(item);
item.setNextItem(head);
There's a lot going on in your code, here's some advice for some of it:
In your Node class: Java naming conventions: the same way that setters should be prefixed with "set," getters should be prefixed with "get:" nextItem() should really be getNextItem().
Also in your Node class: as far as I know, the "next value" field of a node of a linked list is usually a reference to the next Node in the list, and should therefore be of type Node, not just any Object. It should work the way you have it, but using explicit typing is a lot safer. (Please correct me if using "Object" is indeed a common way to construct the next node of a linked list.)
In the first case of remove(), when removing the head: you're looping through the list to reach the last value, presumably to reset its "next value" to the new head, but you're not actually doing it. You want something like this:
if (item == head) {
head = head.nextItem();
for(int i = 0; i < arrSize-1; i++){
cur = cur.nextItem();
}
}
cur.setNextItem(head);
I'm not sure what you hope to accomplish with the second loop.
In the second case of remove(): I'm not sure what you're trying to do with the second while loop - reset all the links in the whole list? The whole point of a linked list is to make that unnecessary. Deleting a node in a linked list does not actually get rid of the object (so you don't have to set item to null). Rather, you simply "go around" the unwanted object and "ignore" it, effectively removing it from the list, as in:
Original list:
[ Value: A; Next: B ] --> [ Value: B; Next: C ] --> [ Value C; Next: D ] ...
After deleting node B:
[ Value: A; Next: C ] --> [Value C; Next: D ] ...
[ Value: B; Next: C ] still exists in memory, but nothing is pointing to it, so it will be removed in the next garbage collection cycle.
To implelement: As you walk the list, keep a reference to the previous node that you visited. Then, once you find the item you're looking for (using correct comparison, as Thomas noted), you can simply set prev.setNextItem(cur.nextItem()); (caveat: untested code):
Node prev = head;
Node cur;
while ((cur = prev.nextItem()) != head) {
if (cur.equals(item)) {
prev.setNextItem(cur.getNextItem());
return true;
}
}
I hope these tips help you along the correct path.

Categories