I have binary tree that is keeping variables and lines they appear on from a .txt file. I previously had put the creation of new nodes mistakenly in the method to check if its contained, which created an abundance of nodes. At that point it printed the correct information but then exited with an error. I realized this and moved it to the insert method, but now print gives me just an error and no results. I have been struggling with this for awhile now and I can't figure out what is wrong with it. Any help would be appreciated greatly.
My code for those 2 methods is:
public void insert(String inputVar, int line, BinaryNode t)
{
if (t.var == null)
{
t.var = inputVar;
t.lines[t.count] = line;
t.count++;
}
else if (inputVar.compareTo(t.var) < 0)
{
if (t.left == null)
t.left = new BinaryNode(100);
insert(inputVar, line, t.left);
}
else if (inputVar.compareTo(t.var) > 0)
{
if (t.right == null)
t.right = new BinaryNode(100);
insert(inputVar, line, t.right);
}
}
public void printTree(BinaryNode t)
{
if (t.var == null)
{
}
else if (t.left == null && t.right !=null)
{
System.out.printf("The variable %s appears at lines ", t.var);
for (int l = 0; l < t.count; l++)
{
System.out.printf("%d ", t.lines[l]);
}
System.out.println();
printTree(t.right);
}
else if (t.right == null && t.left != null)
{
printTree(t.left);
System.out.printf("The variable %s appears at lines ", t.var);
for (int l = 0; l < t.count; l++)
{
System.out.printf("%d ", t.lines[l]);
}
System.out.println();
}
else
{
printTree(t.left);
System.out.printf("The variable %s appears at lines ", t.var);
for (int l = 0; l < t.count; l++)
{
System.out.printf("%d ", t.lines[l]);
}
System.out.println();
printTree(t.right);
}
}
I get an error from the if statement in printTree.
Your base case is t == null, but your code doesn't handle that case. That is, an empty tree is not a node with no variable, but a null node.
Why must your print method be so complicated anyway?
public void printTree( BinaryNode t ) {
if ( null == t )
return;
printTree( t.left );
System.out.printf( "The variable %s appears at lines ", t.var );
for ( int l = 0; l < t.count; l++ )
System.out.printf( "%d ", t.lines[ l ] );
System.out.println();
printTree( t.right );
}
You may reach the last case (else in printTree() ) when both t.right == null && t.left == null so you make a recursive call with both (null) childs and then fall on a NPE in the first check if(t.var == null) where t is null
Related
I was wondering if anyone could assist me with trying to sort three string values into the correct alphabetical order using only if statements?
From my understanding the operator choice that I'm using is for integer values and not strings. Therefore, what operator can I use instead that applies for strings? Incase someone says skip if statements all together and use arrays I can't, if statements only.
MY CODE
String p= "Matt";
String m ="Jack";
String o ="Sam";
if (( p <= m ) && ( m <= o ) )
{
System.out.println("");
}
else if (( p <= m) && ( m <= o ) )
{
System.out.println("");
}
else if (( o <= p ) && ( p <= m ) )
{
System.out.println("");
}
else if (( o <= m ) && ( m <= p ) )
{
System.out.println("");
}
else if (( m <= p ) && ( p <= o ) )
{
System.out.println("");
}
else
{
System.out.println("");
}
Error I'm getting in BlueJ
You're trying to compare strings with <= which is not operable on strings, that's why you get the error stating bad operand type.
You should use string1.compareTo(string2) method to compare two strings. It returns 0 when two strings are equal, negative number if string1 < string2 and positive number if string1 > string2.
Given that, you should do something like this:
String p= "Matt";
String m ="Jack";
String o ="Sam";
if (( p.compareTo(m) <= 0 ) && ( m.compareTo(o) <= 0 ) )
{
System.out.println("");
}
else if (( p.compareTo(m) <= 0 ) && ( m.compareTo(o) <= 0 ) )
{
System.out.println("");
}
else if (( o.compareTo(p) <= 0 ) && ( p.compareTo(m) <= 0 ) )
{
System.out.println("");
}
else if (( o.compareTo(m) <= 0 ) && ( m.compareTo(p) <= 0 ) )
{
System.out.println("");
}
else if (( m.compareTo(p) <= 0 ) && ( p.compareTo(o) <= 0 ) )
{
System.out.println("");
}
else
{
System.out.println("");
}
How about:
if (p.compareTo(m) <= 0) {
if (m.compareTo(o) <= 0) {
System.out.println(p);
System.out.println(m);
System.out.println(o);
} else if (p.compareTo(o) <= 0) {
System.out.println(p);
System.out.println(o);
System.out.println(m);
} else {
System.out.println(o);
System.out.println(p);
System.out.println(m);
}
} else {
if (p.compareTo(o) <= 0) {
System.out.println(m);
System.out.println(p);
System.out.println(o);
} else if (m.compareTo(o) <= 0) {
System.out.println(m);
System.out.println(o);
System.out.println(p);
} else {
System.out.println(o);
System.out.println(m);
System.out.println(p);
}
}
There's a practice problem that I've been working on that's been confusing me.
Define a function treeLevelOrder which satisfies the following claim:
If Q is a binary search tree of integers, then treeLevelOrder(Q) is the String representation of the contents of Q according to their level in the tree.
We get this tree as an example
9
/ \
5 16
/ \ / \
1 7 12 19
The value of the expression treeLevelOrder(Q) in this case would be
"[9,5,16,1,7,12,19]".
I've seen similar problems, but they don't follow the same format that I'm looking for, wanting to print by level order or as ordered tuples. Here's some sample code I've been working on:
private String treeLevelOrder(Node Q)
{
if (Q.left == null && Q.right == null)
return "[" + Q.datum + "]";
else if (Q.left == null && Q.right != null)
return "[" + Q.datum + ", "+Q.right.datum+"]" + treeLevelOrder(Q.right);
else if (Q.left !=null && Q.right == null)
return"[" + Q.datum + ", "+Q.left.datum+", *]"+ treeLevelOrder(T.left);
else
return "[" + Q.datum + ", "+Q.left.datum+", "+Q.right.datum+"]" +
treeLevelOrder(Q.left) + treeLevelOrder(Q.right);
}
Any assistance would be helpful.
EDIT: Okay, so I've been experimenting with the level order example at Geeks for Geeks, thank you curlyBraces, that would be closer to what I'm looking for, though I can't figure out to make it return a string. Here's the code they use:
/* function to print level order traversal of tree*/
void printLevelOrder()
{
int h = height(root);
int i;
for (i=1; i<=h; i++)
printGivenLevel(root, i);
}
/* Compute the "height" of a tree -- the number of
nodes along the longest path from the root node
down to the farthest leaf node.*/
int height(Node root)
{
if (root == null)
return 0;
else
{
/* compute height of each subtree */
int lheight = height(root.left);
int rheight = height(root.right);
/* use the larger one */
if (lheight > rheight)
return(lheight+1);
else return(rheight+1);
}
}
/* Print nodes at the given level */
void printGivenLevel (Node root ,int level)
{
if (root == null)
return;
if (level == 1)
System.out.print(root.data + ", ");
else if (level > 1)
{
printGivenLevel(root.left, level-1);
printGivenLevel(root.right, level-1);
}
}
Any ideas?
Here's an implementation using while loop and two queues to keep track of all the nodes:
public String treeLevelOrder(Node root) {
StringBuilder result = new StringBuilder("");
Queue<Node> current = new LinkedList<>();
Queue<Node> other = new LinkedList<>();
if(root != null)
current.add(root);
while(!current.isEmpty()) {
while(!current.isEmpty()) {
Node node = current.remove();
result.append(",");
result.append(node.datum);
// adding children to the other queue
if(node.left != null)
other.add(node.left);
if(node.right != null)
other.add(node.right);
}
// swapping the queues
Queue<Node> temp = current;
current = other;
other = temp;
}
// building final string
if(result.length() == 0)
result.append("[");
else
result.setCharAt(0,'[');
result.append("]");
return result.toString();
}
I just want you to have a quick look on my AVL-Tree, which I'm programming. I wrote an AVL-Tree and therefore a remove-Method. The problem with this method is that, the other child of the parent of the node (read it please again, sorry that this sounds a bit complicated) which I'm removing, doesn't get printed out, so also gets removed and I dont know why. Here the code:
#Override
public void remove(E value) throws NoSuchElementException {
if(!contains(value)) throw new NoSuchElementException("Doesn't exist!");
else{
root = remove(finds(value).value, root);
}
}
private Node remove(E x, Node t){
if (t==null) {
System.out.println("Sorry but you're mistaken, " + t + " doesn't exist in this tree :)\n");
return null;
}
System.out.println("Remove starts... " + t.value + " and " + x);
if (x.compareTo(t.value) < 0 ) {
t.left = remove(x,t.left);
}
else if (x.compareTo(t.value) > 0) {
t.right = remove(x,t.right);
}
else if(t.left != null) {
t.value = biggest(t.left).value;
remove(t.value, t.left);
}
else
t = (t.left != null) ? t.left : t.right;
return t;
}
AuDTree<Integer> a = new AuDTree<Integer>();
a.insert(7);
a.insert(5);
a.insert(9);
a.insert(4);
a.insert(6);
a.insert(10);
a.insert(8);
a.remove(4);
this is the test. When I remove the "4", the "6" also gets removed. When I remove the "8", the "10" gets removed, and so on. The AVL-Tree looks like this:
7
5 9
4 6 8 10
Thank you in beforehand :)
I have imlemented so far http://pastebin.com/gXJVXdLS
5. Create a remove method. search the tree if the item is found, then you kill it. you have to then balance the tree in AVL fashion to properly fill the hole that you make. Again, use the wikipedia description (which is pretty good) along with the simulator or even maybe my lecture to get the remove working properly. I won't provide sample data on this one-- you can figure that out yourself at this point. just remember that aside from the general case you have two special cases requiring double rotations (see lecture or play with the simulator for cases where you have a left/right or right/left situation.)
Now I need to implement this function
public void remove(K input)
help me in that. I have done this
public void remove(K input) {
root = remove(root,input);
}
public AVLNode<K> remove(K x, AVLNode<K> t) {
if (t==null) {
System.out.println("Sorry but you're mistaken, " + t + " doesn't exist in this tree :)/>\n");
return null;
}
System.out.println("Remove starts... " + t.data + " and " + x);
if (x.compareTo(t.data) < 0 ) {
t.left = remove(x,t.left);
int l = t.left != null ? getHeight(t.left) : 0;
if((t.right != null) && (getHeight(t.right) - l >= 2)) {
int rightHeight = t.right.right != null ? getHeight(t.right.right) : 0;
int leftHeight = t.right.left != null ? getHeight(t.right.left) : 0;
if(rightHeight >= leftHeight)
t = rotateLeft(t);
else
t = rotateRight(t);//double
}
}
else if (x.compareTo(t.data) > 0) {
t.right = remove(x,t.right);
int r = t.right != null ? getHeight(t.right) : 0;
if((t.left != null) && getHeight(t.left) - r >= 2) {
int leftHeight = t.left.left != null ? getHeight(t.left.left) : 0;
int rightHeight = t.left.right != null ? getHeight(t.left.right) : 0;
if(leftHeight >= rightHeight)
t = rotateRight(t);
else
t = rotateLeft(t);//and double
}
}
return t;
} //End of remove...
nvm found the answer
private AVLNode<K> findMin( AVLNode<K> t )
{
if( t == null )
return t;
while( t.left != null )
t = t.left;
return t;
}
public void remove( K x )
{
root = remove( x, root );
}
private AVLNode<K> remove( K x, AVLNode<K> t )
{
if( t == null )
return t; // Item not found; do nothing
int compareResult = x.compareTo( t.data );
if( compareResult < 0 )
t.left = remove( x, t.left );
else if( compareResult > 0 )
t.right = remove( x, t.right );
else if( t.left != null && t.right != null ) // Two children
{
t.data = findMin( t.right ).data;
t.right = remove( t.data, t.right );
}
else
t = ( t.left != null ) ? t.left : t.right;
return t;
}
I have a project I am working on that involves making a database of movies. I have a Movie object and my problem is that I am having trouble printing out Movies that have the same title. Currently only one of the movies is being printed out. I am sure my search function in my BinarySearchTree class is working because it finds it correctly, I think it is stopping once the search condition is met and it doesn't look for any other possible movies with the same title. I think to solve this I just need to implement a loop that will print out each movie as as it is found when traversing the BinarySearchTree.
Here is my search function in BinarySearchTree:
public Node search( Movie m ){
if ( root == null ){
System.out.println("No items to search.");
return null;
}else{
return search( m, root );
}
}
private Node search( Movie m, Node n){
if ( m.compareTo( n.getData() ) == 0 ){
if(n.getLeft() != null){//Go left to continue searching
Node node = search(m, n.getLeft());
if(node != null)
return node;
}
return n;
}else{
if ( n.getRight() == null ){
System.out.println("Item not found.");
return null;
}else{
return search(m, n.getRight());
}
}
}
The implementation in my Main that currently only prints out only one of the movies with the same title (the first one it comes across). I need a loop I think or some way to keep iterating through the tree.
public static BinarySearchTree findByTitle( BinarySearchTree tree ){
Scanner input = new Scanner(System.in);
System.out.println("Enter the title of the movie: ");
Movie temp = new Movie( input.nextLine() );
Node leftMost = tree.search(temp);
if( leftMost != null ){
while(leftMost != null && temp.compareTo( leftMost.getData() ) == 0){
System.out.println(leftMost.getData());
leftMost = leftMost.getRight();
}
}
return tree;
}
First, you can get the left most entry by modifying the search function:
private Node search( Movie m, Node n){
if ( m.compareTo( n.getData() ) == 0 ){
if(n.getLeft() != null){//Go left to continue searching
Node node = search(m, n.getLeft());
if(node != null)
return node;
}
return n;
}
if ( m.compareTo( n.getData() ) < 0 ){
if( n.getLeft() == null){
System.out.println("Item not found.");
return null;
}else{
return search(m, n.getLeft());
}
}else{
if ( n.getRight() == null ){
System.out.println("Item not found.");
return null;
}else{
return search(m, n.getRight());
}
}
After getting the left most node, just keep getting to the right until the movie's title is not equals.
Node leftMost = search(m);
if(leftMost != null){
while(leftMost != null && m.compareTo(leftMost.getData()) == 0){
System.out.println(leftMost.getData());
leftMost = leftMost.getRight();
}
}