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;
}
Related
I have been trying to construct a linked list where there are 3 different ways to view the code, either the current double value or the previous or next node. The problem I seem to be running into is that in essecense I have been creating a new linked list whenever storing the next or previous node of the current node rather than linking it.
This creates 2 problems:
It takes up a ridicolous amount of space
It creates makes bugs and errors common and hard to spot
I want to know if there is a better way to construct linked lists than this method or if I am running into these 2 problems for reasons different than I believe. My code is down below if you want to see what I have been trying to do.
package algs662;
import java.util.*;
//This whole file is about assembling and sorting data
public class BigSort
{
//The Node is an element that represents the current position
//of a linked list and what is immediately to its left or right static class Node
{
//this represents the Node itself
public Node() { }
//this represents its current element
public double item;
//this represents the node to its right
public Node next;
//this represents the node to its left
public Node prev;
}
//this represents the size of the Linked List
int N;
//this is the main node
Node first;
//this is a variable that will be false when the function
//using this hasn't ran once and will be true when it has
public boolean once = false;
//This will create an empty node where new elements can be added
public BigSort()
{
first = null;
N = 0;
checkInvariants ();
}
//This represents the max value
static double max;
private void myassert( String s, boolean b )
{
if( !b ) throw new AssertionError( "Assertion failed: " + s );
}
private void checkInvariants()
{
myassert( "Empty <==> first==null", (N == 0) == (first == null) );
Node x = first;
for( int i = 0; i < N; ++i )
{
if( x==null )
{
throw new Error( "List too short!" );
}
x = x.next;
}
myassert("EndOfList == null", x == null);
}
private Node reset( Node n )
{
Node saved;
while( n.prev != null )
{
saved = n;
n = n.prev;
}
return n;
}
//This function will delete a specific number from a list
private void delete( double num )
{
if( once == false )
{
Node curr = first;
if( N == 0 ) { throw new Error( "There is no list" ); }
else if( N == 1 )
{
if( curr.item == num )
{
first = null;
return;
}
else
{
throw new Error( "Number inputted doesn't exist" );
}
}
else if( curr != null )
{
if( curr.item == num )
{
first = curr.next;
--N;
return;
}
while( curr.next != null )
{
if( curr.next.item != num )
{
curr.prev = curr;
curr = curr.next;
}
else if( curr.next.item == num )
{
curr.next = curr.next.next;
--N;
reset( curr );
return;
}
}
if( curr.item == num )
{
first = curr.prev;
curr.next = null;
--N;
reset( curr );
return;
}
else if( curr.next == null )
{
throw new Error( "Number inputted doesn't exist" );
}
}
}
else
{
return;
}
}
private void push( double i )
{
Node temp = new Node();
temp.item = i;
Node saved;
Node curr = first;
if( this.first == null )
{
first = temp;
return;
}
else
{
while( curr.next != null )
{
saved = curr;
curr = curr.next;
curr.prev = saved;
}
saved = curr;
curr.next = temp;
curr = curr.next;
curr.prev = saved;
}
this.N++;
first = reset( curr );
}
private void pushFront( double i )
{
Node temp = new Node();
Node saved;
temp.item = i;
temp.next = first;
saved = temp;
temp = temp.next;
temp.prev = saved;
temp = temp.prev;
++N;
first = temp;
}
private void pushPos( int pos, double i )
{
Node temp = new Node();
Node store = new Node();
Node last = new Node();
store.item = i;
temp = first;
Node saved;
double pastval;
double savedval;
if( pos > N || pos < 0 )
{
throw new Error( "The position inputted doesn't exist" );
}
else
{
if( pos == 0 )
{
store.item = i;
store.next = first;
++N;
first = store;
return;
}
for( int x = 0; x < pos; ++x )
{
saved = temp;
temp = temp.next;
temp.prev = saved;
}
pastval = temp.item;
temp.item = i;
temp = temp.next;
savedval = temp.item;
temp.item = pastval;
while( temp.next != null )
{
// Does nothing??
}
first=reset( temp );
return;
}
}
private double pop()
{
Node popped;
Node temp = first;
while( temp.next.next !=null )
{
temp = temp.next;
}
popped = temp.next;
temp.next = null;
--N;
System.out.print( popped );
first = temp;
return popped.item;
}
private void incurSort()
{
double swap = 0;
int u = 0;
for( int y = 1; y < N - 1; ++y )
{
//this compares the current item to the next item
if( first.item > first.next.item )
{
u = y;
while( u > 0 && first.prev != null )
{
if( first.item > first.next.item )
{
swap = first.item;
first.item = first.next.item;
first.next.item = swap;
}
first = first.prev;
--u;
}
}
while( u < y && first.next != null )
{
first = first.next;
++u;
}
}
reset(first);
}
public static void main( String args[] )
{
double swap = 0;
BigSort b = new BigSort();
int u = 0;
// Adding elements in the list
// using add() method
b.push( 1.0 );
b.push( 3.0 );
b.push( 5.0 );
b.push( 2.0 );
b.push( 20.0 );
b.push( 11.0 );
b.push( 13.0 );
b.push( 17.0 );
Node two = b.first;
b.incurSort();
b.delete( 11.0 );
b.delete( 1.0);
b.delete( 20.0);
b.delete( 5.0);
b.delete( 3.0);
b.delete( 13.0);
b.pushFront( 10.0);
b.pushFront( 2.0 );
b.pushFront( 16.0 );
b.pushFront( 50.0 );
b.pushFront( 100.0 );
b.pushPos( 2, 20.0 );
System.out.println( b.pop() );
System.out.println( b.pop() );
System.out.println( b.pop() );
System.out.println( b.pop() );
System.out.println( b.pop() );
System.out.println( b.pop() );
System.out.println( "stuff left over" );
for( int k = 0; k <= b.N - 1; ++k )
{
if( b.first != null )
{
System.out.println( b.first.item );
b.first = b.first.prev;
}
else
{
System.out.println( "it broke at " + k );
break;
}
}
}
}
The accepted answer can make a Perfect tree (which is also a Complete tree). Although it cannot make a Complete tree without being Perfect. It was the closest answer to my request though. To make a compete the without being Perfect too, you could remove the rightmost leaves of the tree.
1. Problem:
Trying to make a Binary Search Tree into a Complete Binary Search Tree. I can find lots of code examples for a Complete Binary Tree, but no Complete Binary Search Tree. The insert is working as a Binary Search Tree should. But this way of inserting is not a Complete Tree. If I add a bunch of random numbers, it will not be a Complete tree. How can I make the code insert to the tree but at the same time be a complete binary search tree?
I would greatly appreciate a code example. I don't find it hard to understand it in theory at all, but very hard to implement it in code.
2. What I tried:
To add the nodes in a level order way.
While loop "Insert as long as the height is not 6 and all nodes are full nodes except leaves".
"Add only to the right child if the value is greater than the parent and if the left child is not null".
Arrays and LinkedLists to add from.
3. How I insert:
private BinaryNode<AnyType> insert( AnyType x, BinaryNode<AnyType> t )
{
if( t == null )
return new BinaryNode<>( x, null, null);
int compareResult = x.compareTo( t.element );
if (compareResult < 0)
t.left = insert(x, t.left);
else if (compareResult > 0)
t.right = insert(x, t.right);
else
; // Duplicate; do nothing
return t;
}
The AnyType is the value to be inserted, the BinaryNode is the
current node.
4. What the program is able to do:
Insert and remove.
Find Height, minimum, maximum or specific node.
Preorder, Postorder, Levelorder, and Inorder searches.
Get the number of full nodes, number of all nodes, and number of leaves.
5. Full program:
import java.nio.BufferUnderflowException;
import java.util.LinkedList;
import java.util.Queue;
import java.util.Random;
/**
* Implements an unbalanced binary search tree.
* Note that all "matching" is based on the compareTo method.
* #author Mark Allen Weiss
*/
public class ExerciseBinarySearchTree03<AnyType extends Comparable<? super AnyType>>
{
/**
* Construct the tree.
*/
public ExerciseBinarySearchTree03( )
{
root = null;
}
public void preOrder(){
System.out.println("\nPre Order ");
preOrder(root);
}
public void postOrder(){
System.out.println("\nPost Order ");
postOrder(root);
}
public void inOrder(){
System.out.println("\nIn Order ");
inOrder(root);
}
public void levelOrder(){
System.out.println("\nLevel Order ");
levelOrder(root);
}
public int numberOfNodes(){
return numberOfNodes(root);
}
public int numberOfFullNodes(){
return numberOfFullNodes(root);
}
public int numberOfLeaves(){
return numberOfLeaves(root);
}
/**
* Insert into the tree; duplicates are ignored.
* #param x the item to insert.
*/
public void insert( AnyType x )
{
root = insert( x, root );
}
/**
* Remove from the tree. Nothing is done if x is not found.
* #param x the item to remove.
*/
public void remove( AnyType x )
{
root = remove( x, root );
}
/**
* Find the smallest item in the tree.
* #return smallest item or null if empty.
*/
public AnyType findMin( )
{
if( isEmpty( ) )
throw new BufferUnderflowException( );
return findMin( root ).element;
}
/**
* Find the largest item in the tree.
* #return the largest item of null if empty.
*/
public AnyType findMax( )
{
if( isEmpty( ) )
throw new BufferUnderflowException( );
return findMax( root ).element;
}
/**
* Find an item in the tree.
* #param x the item to search for.
* #return true if not found.
*/
public boolean contains( AnyType x )
{
return contains( x, root );
}
/**
* Make the tree logically empty.
*/
public void makeEmpty( )
{
root = null;
}
/**
* Test if the tree is logically empty.
* #return true if empty, false otherwise.
*/
public boolean isEmpty( )
{
return root == null;
}
/**
* Print the tree contents in sorted order.
*/
public void printTree( )
{
if( isEmpty( ) )
System.out.println( "Empty tree" );
else
printTree( root );
}
/**
* Internal method to insert into a subtree.
* #param x the item to insert.
* #param t the node that roots the subtree.
* #return the new root of the subtree.
*/
private BinaryNode<AnyType> insert( AnyType x, BinaryNode<AnyType> t )
{
if( t == null )
return new BinaryNode<>( x, null, null);
int compareResult = x.compareTo( t.element );
if (compareResult < 0)
t.left = insert(x, t.left);
else if (compareResult > 0)
t.right = insert(x, t.right);
else
; // Duplicate; do nothing
return t;
}
/* Given a binary tree, return true if the tree is complete
else false */
static boolean isCompleteBT(BinaryNode root)
{
// Base Case: An empty tree is complete Binary Tree
if(root == null)
return true;
// Create an empty queue
Queue<BinaryNode> queue =new LinkedList<>();
// Create a flag variable which will be set true
// when a non full node is seen
boolean flag = false;
// Do level order traversal using queue.
queue.add(root);
while(!queue.isEmpty())
{
BinaryNode temp_node = queue.remove();
/* Check if left child is present*/
if(temp_node.left != null)
{
// If we have seen a non full node, and we see a node
// with non-empty left child, then the given tree is not
// a complete Binary Tree
if(flag == true)
return false;
// Enqueue Left Child
queue.add(temp_node.left);
}
// If this a non-full node, set the flag as true
else
flag = true;
/* Check if right child is present*/
if(temp_node.right != null)
{
// If we have seen a non full node, and we see a node
// with non-empty right child, then the given tree is not
// a complete Binary Tree
if(flag == true)
return false;
// Enqueue Right Child
queue.add(temp_node.right);
}
// If this a non-full node, set the flag as true
else
flag = true;
}
// If we reach here, then the tree is complete Bianry Tree
return true;
}
/**
* Internal method to remove from a subtree.
* #param x the item to remove.
* #param t the node that roots the subtree.
* #return the new root of the subtree.
*/
private BinaryNode<AnyType> remove( AnyType x, BinaryNode<AnyType> t )
{
if( t == null )
return t; // Item not found; do nothing
int compareResult = x.compareTo( t.element );
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.element = findMin( t.right ).element;
t.right = remove( t.element, t.right );
}
else
t = ( t.left != null ) ? t.left : t.right;
return t;
}
/**
* Internal method to find the smallest item in a subtree.
* #param t the node that roots the subtree.
* #return node containing the smallest item.
*/
private BinaryNode<AnyType> findMin( BinaryNode<AnyType> t )
{
if( t == null )
return null;
else if( t.left == null )
return t;
return findMin( t.left );
}
/**
* Internal method to find the largest item in a subtree.
* #param t the node that roots the subtree.
* #return node containing the largest item.
*/
private BinaryNode<AnyType> findMax( BinaryNode<AnyType> t )
{
if( t != null )
while( t.right != null )
t = t.right;
return t;
}
/**
* Internal method to find an item in a subtree.
* #param x is item to search for.
* #param t the node that roots the subtree.
* #return node containing the matched item.
*/
private boolean contains( AnyType x, BinaryNode<AnyType> t )
{
if( t == null )
return false;
int compareResult = x.compareTo( t.element );
if( compareResult < 0 )
return contains( x, t.left );
else if( compareResult > 0 )
return contains( x, t.right );
else
return true; // Match
}
/**
* Internal method to print a subtree in sorted order.
* #param t the node that roots the subtree.
*/
private void printTree( BinaryNode<AnyType> t )
{
if( t != null )
{
printTree( t.left );
System.out.println( t.element );
printTree( t.right );
}
}
/**
* Internal method to compute height of a subtree.
* #param t the node that roots the subtree.
*/
private int height( BinaryNode<AnyType> t )
{
if( t == null )
return -1;
else
return 1 + Math.max( height( t.left ), height( t.right ) );
}
public int height(){
return height(root);
}
private void preOrder(BinaryNode t )
{
if (t == null) {
return;
}
System.out.println(t.element + " ");
preOrder(t.left);
preOrder(t.right);
}
private void postOrder(BinaryNode t){
if (t == null) {
return;
}
postOrder(t.left);
postOrder(t.right);
System.out.println(t.element + " ");
}
private void inOrder(BinaryNode t)
{
if (t == null) {
return;
}
inOrder(t.left);
System.out.println(t.element + " ");
inOrder(t.right);
}
private void levelOrder(BinaryNode root) {
if (root == null) {
return;
}
Queue<BinaryNode> q = new LinkedList<>();
// Pushing root node into the queue.
q.add(root);
// Executing loop till queue becomes
// empty
while (!q.isEmpty()) {
BinaryNode curr = q.poll();
System.out.print(curr.element + " ");
// Pushing left child current node
if (curr.left != null) {
q.add(curr.left);
}
// Pushing right child current node
if (curr.right != null) {
q.add(curr.right);
}
}
}
//O(n) for the below three methods.
private int numberOfNodes(BinaryNode<AnyType> root){
if ( root == null ) {
return 0;
}
return 1 + numberOfNodes( root.left ) + numberOfNodes( root.right );
}
private int numberOfLeaves(BinaryNode<AnyType> t){
if( t == null ) {
return 0;
}
if( t.left == null && t.right == null ) {
return 1;
}
return numberOfLeaves(t.left) + numberOfLeaves(t.right);
}
private int numberOfFullNodes(BinaryNode<AnyType> root){
if(root==null) {
return 0;
}
if(root.left!=null && root.right!=null) {
return 1 + numberOfFullNodes(root.left) + numberOfFullNodes(root.right);
}
return numberOfFullNodes(root.left) + numberOfFullNodes(root.right);
}
// Basic node stored in unbalanced binary search trees
private static class BinaryNode<AnyType>
{
// Constructors
BinaryNode( AnyType theElement )
{
this( theElement, null, null );
}
BinaryNode( AnyType theElement, BinaryNode<AnyType> lt, BinaryNode<AnyType> rt )
{
element = theElement;
left = lt;
right = rt;
}
AnyType element; // The data in the node
BinaryNode<AnyType> left; // Left child
BinaryNode<AnyType> right; // Right child
}
/** The tree root. */
private BinaryNode<AnyType> root;
AnyType[] arr = (AnyType[]) new Integer[7];
// Test program
public static void main( String [ ] args ) {
ExerciseBinarySearchTree03<Integer> bst = new ExerciseBinarySearchTree03<>( );
final int NUMS = 20;
final int GAP = 37;
System.out.println( "Checking... (no more output means success)" );
bst.insert(10);
for( int i = GAP; i != 0; i = ( i + GAP ) % NUMS ) {
if(i != 10) {
bst.insert(i);
}
}
for( int i = 1; i < NUMS; i+= 2 )
bst.remove( i );
if( NUMS <= 40 )
bst.printTree( );
if( bst.findMin( ) != 2 || bst.findMax( ) != NUMS - 2 )
System.out.println( "FindMin or FindMax error!" );
for( int i = 2; i < NUMS; i+=2 )
if( !bst.contains( i ) )
System.out.println( "Find error1!" );
for( int i = 1; i < NUMS; i+=2 )
{
if( bst.contains( i ) )
System.out.println( "Find error2!" );
}
bst.inOrder();
}
}
If you think a bit, you will see that with the usual insert function the order of the elements determines the shape of the tree.
if you enter 2,1,3 or 2,3,1 you will get the level 2 complete binary tree.
if you enter 4,2,6,1,3,5,7 you will get the level 3 complete binary tree.
if you enter 8,4,12,2,6,11,13,1,3,5,7,9,10,14,15 you will get level 4 complete binary tree.
here a pseudo code that recursively supplies the elements, initial call must be
getMedium( v , 0 , v.lenght)
getMedium( array v , start , finish)
if start == finish
insert(v[start])
return
insert( v[(finish - start)/2]
getMedium( array v , start , (finish - start)/2 -1)
getMedium( array v , (finish - start)/2+1 , finish)
The solution is to use recursion, I made a new post where I got an answer:
https://stackoverflow.com/a/52749727/9899617
I have been working on creating a Binary Tree from scratch, not using built-in libraries. I am working on a function called "pruneLeaves". The job is to remove all leaves of the tree; nodes with no children.
When I step through the function with breakpoints, it appears to be removing the leaves and even prints out that it is indeed removing the proper nodes. However, when I display the tree in my main function afterwards, the nodes are still there!
I have tried for hours to figure this out, what am I overlooking?!
Program Output:
Num nodes = 9
Pruning.
12
Leaf removed
9
Leaf removed
4
Leaf removed
Tree after pruning..
3 4 5 6 7 8 9 11 12
// Recursive helper. Accepts BinaryNode as a parameter
private BinaryNode pruneLeaves(BinaryNode t) {
// If we have no left child AND no right child, we are a leaf
if ((t.left == null) && (t.right == null)) {
//Print the element being removed.
System.out.println (t.element);
//Remove the element
t = remove(t.element, t);
if(t == null)
System.out.println("Leaf removed");
}
// Else we have at least one child
else {
if (t.right != null) {
pruneLeaves(t.right);
}
if (t.left != null) {
pruneLeaves(t.left);
}
}
//Return our leafless tree
return t;
}
// Main recursive method, call the helper method by passing the root of the
// tree, which calls it.
public void pruneLeaves () {
pruneLeaves(this.getRoot());
}
BinaryNode getRoot () {
return this.root;
}
/**
* Internal method to remove from a subtree.
* #param x the item to remove.
* #param t the node that roots the tree.
* #return the new root.
*/
private BinaryNode remove( int x, BinaryNode t ) {
success = false;
if( t == null )
return t; // Item not found; do nothing
if( x < t.element )
t.left = remove( x, t.left );
else if( x > t.element )
t.right = remove( x, t.right );
else {
success = true;
if( t.left != null && t.right != null ) { // Two children
t.element = findMin( t.right ).element;
t.right = remove( t.element, t.right );
}
else
t = ( t.left != null ) ? t.left : t.right;
}
return t;
}
And my main method, calling the function:
public static void main( String [ ] args ) {
BST t = new BST( );
t.insert(7);
t.insert(6);
t.insert(5);
t.insert(3);
t.insert(4);
t.insert(8);
t.insert(11);
t.insert(9);
t.insert(12);
System.out.println();
System.out.println ("Num nodes = " + t.countNodes());
System.out.println ("Pruning.");
// Remove leaves of the tree
t.pruneLeaves();
t.infix();
System.out.println();
}
Using the link: Deleting Leaves From a Binary Tree
I have found the errors in my code and corrected them using the answer given in the link.
Correct Code as follows:
private BinaryNode pruneLeaves (BinaryNode p) {
// There is a left child
if (p.left != null)
if (isLeaf(p.left)) //Is that child a leaf?
p.left = null;
else
pruneLeaves(p.left); // If it is not, recursive call
// Is there a right child
if (p.right != null)
if (isLeaf(p.right))
p.right = null;
else
pruneLeaves(p.right); // Recursive call
return p;
}
// Main recursive call, passes the root of calling tree to the helper method
public void pruneLeaves () {
pruneLeaves (this.getRoot());
}
// Returns true if child is a leaf
boolean isLeaf (BinaryNode t) {
if (t.left == null && t.right == null) {
return true;
}
return false;
}
+1 for being right answer (only one I've found so far), but you forgot the null scenario for the root, and also to remove the root if the root itself has no children. Here's how I did it - I used your code and then made sure it fit all scenarios:
public void removeLeaves () {
if (root != null) {
removeLeaves (root);
} else {
return;
}
}
private Node removeLeaves (Node node) {
if (root.left == null && root.right == null) {
root = null;
} else {
if (node.left != null) {
if (node.left.left == null && node.left.right == null) {
node.left = null;
} else {
removeLeaves(node.left);
}
}
if (node.right != null) {
if (node.right.left == null && node.right.right == null) {
node.right = null;
} else {
removeLeaves(node.right);
}
}
}
return node;
}
This code ensures that all nodes with no children are removed, and also eliminates the need for the isLeaf() function.
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
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
I have binary search tree code (It is hard code) doing ( insert , delete , max , min , sort and lookup ) and I want study efficancy for BST . I want create a random method to generate 1000 numbers rather than I enter number .
How can I create this method ?
public class BinarySearchTree {
private Node root;
private static class Node {
Node parent;
Node left;
Node right;
int data;
Node( int data ) {
this.data = data;
}
#Override
public String toString( ) {
return "" + data;
}
}
public void insert( int data ) {
root = insert( root, data );
}
public Node insert( Node node, int data ) {
if( node == null ) {
node = new Node( data );
} else if( data < node.data ) {
node.left = insert( node.left, data );
node.left.parent = node;
} else {
node.right = insert( node.right, data );
node.right.parent = node;
}
return node;
}
private void swap( Node a, Node b ) {
if( a.parent == null ) {
root = b;
} else if( a == a.parent.left ) {
a.parent.left = b;
} else {
a.parent.right = b;
}
if( b != null ) {
b.parent = a.parent;
}
}
public void delete( int data ) {
delete( root, data );
}
public void delete( Node node, int data ) {
if( node == null ) {
return;
}
else if ( data == node.data) {
if( node.left == null ) {
swap( node, node.right );
}
else if( node.right == null ) {
swap( node, node.left );
}
else {
Node minNode = node.right;
while( minNode.left != null ) {
minNode = minNode.left;
}
if( minNode.parent != node ) {
swap( minNode, minNode.right );
minNode.right = node.right;
minNode.right.parent = minNode;
}
swap( node, minNode );
minNode.left = node.left;
minNode.left.parent = minNode;
}
}
// Continue searching in the left subtree.
else if( data < node.data) {
delete( node.left, data );
}
// Continue searching in the right subtree.
else {
delete( node.right, data );
}
}
public boolean lookup( int data ) {
return lookup( root, data );
}
public boolean lookup( Node node, int data ) {
if( node == null ) {
// Can't find it.
return false;
} else if( data == node.data) {
// Found it.
return true;
} else if( data < node.data) {
// Search left subtree.
return lookup( node.left, data );
} else {
// Search right subtree.
return lookup( node.right, data );
}
}
public int minValue( ) {
return minValue( root );
}
public int minValue( Node node ) {
Node cursor = node;
while( cursor.left != null ) {
cursor = cursor.left;
}
return cursor.data;
}
public int maxValue( ) {
return maxValue( root );
}
public int maxValue( Node node ) {
Node cursor = node;
while( cursor.right != null ) {
cursor = cursor.right;
}
return cursor.data;
}
public void inorderTraversal( ) {
inorderTraversal( root );
}
private void inorderTraversal( Node node ) {
if( node != null ) {
inorderTraversal( node.left );
System.out.print( node.data + " " );
inorderTraversal( node.right );
}
}
public static void main( String[ ] args ) {
BinarySearchTree bst = new BinarySearchTree( );
int[ ] input = new int[ ] { 5, 10, 3, 9, 7, 8 , 1 , 4 , 6 , 10};
for( int i : input ) {
bst.insert( i );
}
bst.delete( 5 );
bst.delete( 10 );
bst.delete( 3 );
bst.delete( 7 );
System.out.println( "\n Sorted :" );
bst.inorderTraversal( );
System.out.println( "\nMax Value:" );
System.out.println(bst.maxValue());
System.out.println( "\n Min Value:" );
System.out.println(bst.minValue());
System.out.println(bst.lookup(1));
}
}
You might be interested in java.util.Random:
import java.util.Random;
...
Random random = new Random(System.currentTimeMillis());
random.nextInt();
Note that Random only creates pseudorandom numbers, so you'll have to use a sufficiently unique seed.
I second the java.util.Random suggestion. Do you really want to store an array of them or do you want to just ask the Random generator for a random number between 0 and 999, 1000 times? Here's a function to get an array of them, but I would just forgo the array and loop through the Random 1000 times.
public static int[] generateRandomNumbers( int size ) {
if ( size <= 0 ) {
throw new IllegalArgumentException( "size must be greater than 0" );
}
Random random = new Random( System.currentTimeMillis() );
int[] results = new int[ size ];
for ( int i = 0; i < size; i++ ) {
results[ i ] = random.nextInt( size );
}
return results;
}
...all other things equal, make your main like this and you've got a working program. I don't know whether it is correct or not, it works...
public static void main( String[] args ) {
BinarySearchTree bst = new BinarySearchTree();
int[] randoms = generateRandomNumbers( 1000 );
for ( int i : randoms ) {
bst.insert( i );
}
bst.delete( randoms[ 5 ] );
bst.delete( randoms[ 10 ] );
bst.delete( randoms[ 3 ] );
bst.delete( randoms[ 7 ] );
System.out.println( "\n Sorted :" );
bst.inorderTraversal();
System.out.println( "\nMax Value:" );
System.out.println( bst.maxValue() );
System.out.println( "\n Min Value:" );
System.out.println( bst.minValue() );
System.out.println( bst.lookup( randoms[ 1 ] ) );
System.out.println( bst.lookup( randoms[ 999 ] ) );
}
This will give you 1000 random integers between MIN and MAX, including MIN but not including MAX.
int MIN;
int MAX;
int[] randoms = new int[1000];
Random randGen = new Random();
for(int i = 0; i < randoms.length; i++)
{
randoms[i] = MIN + randGen.nextInt(MAX - MIN));
}