Hash Table/Binary Search Tree question
I'm creating a hash table that uses a Binary Search Tree in each element to handle collisions. I isolated the problem to where and how it occurs to two lines of code; here is the relevant code(There is a working method "insert(String s)" in the BinarySearchTree class):
x = new BinarySearchTree[size];
x[0].insert("pppppp");When I try to insert ANY String into ANY array element of x (not just 0), I get a NullPointerException. Keep in mind that BinarySearchTree works perfectly when it's not an array.
Message was edited by:
rpelep
x = new BinarySearchTree[size];
x[0].insert("pppppp");You should know that when you allocate an array of objects, each entry is initialized to null.
Instead, you must do this:
x = new BinarySearchTree[size];
for(int i=0; i<size; i++) {
x[i] = new BinarySearchTree();
}After that, you can then do
x[0].insert("pppppp");
Similar Messages
-
Basic binary search tree question
Hi,
I was just wondering, if there's a binary search tree that holds objects can the binary search tree be based on any of the attributes in those objects.
So for example say we have a Person object and it has the attributes name, age, and height. Can we make a binary search tree based on the age or a search tree based on just the height.
And lastly how would that be done in the comparable method.
Thanks.Of course it depends on what (and whether) the Person class implements for Comparable. If you want to base the tree on the default comparison (i.e., the one that compareTo does) then you don't need a separate Comparator.
When you write your binary tree implementation, it's wise to make it smart enough to either take a Comparator, or to use the default comparison (if the objects being tracked implement Comparable).
Note that Comparators and Comparable have nothing to do with trees per se. It's not like a tree necessarily needs one or the other. It's simply very smart to use the existing Java framework to determine an order among objects. -
I am writing my own implementation of a binary search tree and one of the methods I am having issues with writing is a getRootNode() method.
I am wondering A if there is any API doc on Binary search trees and B What the method would look like for a getRootNode()
I wrote the following two methods
//getEntry
public E getEntry(E entry)
return findEntry(getRootNode(), entry);
//findEntry
private E findEntry(BinarySearchTreeNode<E> rootNode, E entry)
E resualt = null;
if (rootNode == null)
E rootEntry = rootNode.getElement();
if (entry.equals(rootEntry))
resualt = rootEntry;
else if(entry.compareTo(rootEntry) < 0)
resualt = findEntry(rootNode.getLeft(), entry);
else
resualt = findEntry(rootNode.getRight(), entry);
return resualt;
//getRootNode -- this is where I am lost
private BinarySearchTreeNode<E> getRootNode() {
// TODO Auto-generated method stub
return null;
}Any Ideas?user8974754 wrote:
initialized root
private BinarySearchTreeNode<E> root;
That doesn't initialize it. That just declares a member variable named root. To initialize it, you have to do root = something, either on the line where you declare it or elsewhere. Until then, it will have its default value of null.
>
So then I am assuming then the code would be
//Going based on some other code
private BinarySearchTreeNode<E> getRootNode() {
if (root != null)
return root;
else
return null;
That's the same as just return root; If it's not null, you return it, and if it is null, you return null, which is the same as returning root, since, as we just established, root is null.
Edited by: jverd on Dec 13, 2010 5:02 PM -
Binary Search Tree Question - Duplicate Entries
I am doing a project for school where I have to parse a web page into a binary search tree. The problem I'm encountering is that the tree is not supposed to have duplicate entries. Instead, each node has a count variable which is supposed to be incremented if a duplicate node attempts to be inserted. I have everything else working but I can't seem to get the count to increment.
Here is the insert method in my BinarySearchTree class:
public void insert( String s )
BTNode newNode = new BTNode();
newNode.sData = s;
newNode.count = 1;
if( root == null )
root = newNode;
else
BTNode current = root;
BTNode parent;
while( true )
parent = current;
if( s.compareTo( current.sData ) < 0 )
current = current.leftChild;
if( current == null )
parent.leftChild = newNode;
return;
else if( s.compareTo( current.sData ) >= 0 )
current = current.rightChild;
if( current == null )
parent.rightChild = newNode;
return;
}Thanks for the help!runningfish007 wrote:
I am doing a project for school where I have to parse a web page into a binary search tree. The problem I'm encountering is that the tree is not supposed to have duplicate entries. Instead, each node has a count variable which is supposed to be incremented if a duplicate node attempts to be inserted. There are two ways I can think to do this simply. Presumably you have a search method that returns a BTNode for a given String? You could use that to find out if the tree already contains that String. If so, you have that Node, so you can just increment it's counter. If not, then go through and insert it normally, knowing that you won't encounter a duplicate.
The second is to look at the children for each node as you come to it. If either matches the given string, then you've found a duplicate. Otherwise, either insert the new element there (if that's the location it belongs), or continue down the tree.
Either way, I'd rewrite this as a recursive method. It's much simpler. What you do is check if the new element should be a child of the current node. If so, attach it and return. Otherwise, call the method on the correct child node. No looping necessary. -
Question about binary search tree
i was asked to do a programe that generating 1000 random integer numbers between 1 - 50, storing each unique number and it's corresponding occurrence into a binary search tree and output them in asending order. Therefore, before, adding the new number into the tree, i have to compare it with others that have been stored in the tree. and i did it in the following code segment.
public void compare(int number)
NumberObject newNumObj = new NumberObject(number);
boolean b = true;
if(isEmpty())
root = new BinarySearchTreeNode(newNumObj, null, null); //assuming BSTNode class in somewhere else
else
b = find(root, newNumObj);
if(b == false)
add(newNumObj);
private boolean find(BinarySearchTreeNode node, NumberObject newNumObj)
int relation = ((Comparable)newNumObj).compareTo(node.getObject());
//******************** QUESTION IS HERE ******************
if(relation == 0)
(node.getObject()).setCount(); //increase that number object's account
newNumObj = null; //recycle newNumObj if it's the same as one stored in the tree
return true;
//****************** ENDS QUESTION ********************************
else if(relation > 0)
find(node.right, newNumObj);
else if(relation < 0)
find(node.left, newNumObj);
return false;
my question is can i say the new number is the same as the one that already stored in the tree according to the above code? i am not sure cauz there are two attributes: the number and it's frequency stored in one numberObject. and the compareTo method just dealing with the numbers, but nothing particular associated with it's account. so, could anyone help me work out this puzzle? help would be greatly appreciated!Not sure whether this is what you want.. But may be it will help....
import java.util.*;
public class Rand{
public static void main(String arg[]){
new Rand();
Rand(){
Random random=new Random();
int ranNo;
TreeMap map=new TreeMap();
Integer in;
for(int i=0;i<1000;i++){
ranNo= random.nextInt() ;
ranNo=Math.abs(ranNo);
ranNo%=50;
in=new Integer(ranNo);
if(!(map.containsKey(in)))
map.put(in,i+"");
Iterator iter=map.keySet().iterator();
Integer key;
while(iter.hasNext()){
System.out.print( (key=(Integer)iter.next()) + " ");
System.out.println(map.get(key).toString());
}appu -
Storing strings in binary search tree
On the below code I get: ClassCastException : java.lang.String . I am trying to build a binary search tree from a text file one word at a time. when I call this method below the first time it works fine, but on the second call it gets the error at the second if statement:
getInfo() returns a String
public void insertBST(Object o) {
TreeNode p, q;
TreeNode r = new TreeNode(o);
if (root == null)
root = r;
else {
p = root;
q = root;
while (q != null) {
p = q;
System.out.println(r.getInfo());
if (((TreeComparable)(r.getInfo())).compareTo((TreeComparable)(p.getInfo())) < 0)
q = p.getLeft();
else
q = p.getRight();
if (((TreeComparable)(r.getInfo())).compareTo((TreeComparable)(p.getInfo())) < 0)
setLeftChild(p, r);
else
setRightChild(p, r);
}------------ This is the code I use to call on the above function:
public void readFromFile() {
//int i = 1;
while (fileScan.hasNext()) {
String buf = fileScan.next();
hash(buf);
if (table[tableIndex] == tableIndex) {
System.out.println("Same Omitted Word");
else{
obt.insertBST(buf);
System.out.println("Not an Omitted Word");
public int hash(String s) {
sum = 0;
for(int i = 0; i< s.length(); i++)
sum += (int)s.charAt(i);
tableIndex = sum%TABLESIZE;
return tableIndex;
-------------------Also, this interface is used by the insertBST function:
public interface TreeComparable {
public int compareTo(Object o);
public void operate(Object o);
public void visit();We got the inserBST() funtion from the instructor, it is in a ObjectBinaryTree class we should use to build the tree, also we received the TreeComparable interface which inserBST() uses from the instructor.
One one part of the assigment it says"
Note that while the TreeNode class is built to hold a generic Object, you'll be creating a Word class whose objects will be placed in the TreeNode's of the Binar search tree. Each Word object should provide the followinf fields:
a reference to the word, an int to count the nomber of times it apears.
Which I have not done, I'm simply passing the String as I read it from the file.
Now, I'm thinking TreeComparable is acting as an Int object and is trying to cast a String which produces the error.
Also, I have used this where the inserBST():
public class ObjectBinaryTree implements TreeComparable {
but then I get a message that it cant override one of the methods in TreeComparable.
This is the rest of the class I'm using to implement the ObjectBinayTree class.
public void readFromFile() {
//int i = 1;
while (fileScan.hasNext()) {
String buf = fileScan.next();
// System.out.println(buf);
hash(buf);
// System.out.println(tableIndex);
if (table[tableIndex] == tableIndex) {
//System.out.println("Same Omitted Word");
else{
//obt.insertBST(buf);
//System.out.println("Not an Omitted Word");
public void makeHashTable() {
while (fileScan.hasNext()) {
String buf = fileScan.next();
hash(buf);
if (table[tableIndex] == 0)
table[tableIndex] = sum%TABLESIZE;
else{
do{
tableIndex++;
}while( table[tableIndex] != 0);
table[tableIndex] = sum % TABLESIZE;
public int hash(String s) {
sum = 0;
for(int i = 0; i< s.length(); i++)
sum += (int)s.charAt(i);
tableIndex = sum%TABLESIZE;
return tableIndex;
} -
Hi all,
Can i use raed table binary search for Hased tables? I coded like this
DATA:T_MODEL_HASH LIKE HASHED TABLE OF T_MODEL
WITH UNIQUE KEY PBPINO WITH HEADER LINE.
READ TABLE t_model_hash WITH KEY pbpino = t_zwpbph-pbpapino
BINARY SEARCH.
But iam getting syntax error "cannot use explicit or implicit index operations on hased tables ".can any one let me know about this issue?Hi Priya,
Hashed tables are managed by a hash algorithm. There is no logical index. The entries are not ordered in the memory. The position of a row is calculated by specifying a key using a hash function.
A hashed table's performance in reads is NOT dependent on the number of records. However, it is intended for reads that will return only and only one record. It uses a "side-table" with a hash algorithm to store off the physical location of the record in the actual internal table. It is not NECESSARILY sorted/organized in an meaningful order (like a sorted table is). Please note that changes to a hashed tables records must be managed carefully.
Please check this link to understand how to use hash table.
http://help.sap.com/saphelp_erp2004/helpdata/en/fc/eb362c358411d1829f0000e829fbfe/frameset.htm
Regards,
Ferry Lianto -
Binary search tree in java using a 2-d array
Good day, i have been wrestling with this here question.
i think it does not get any harder than this. What i have done so far is shown at the bottom.
We want to use both Binary Search Tree and Single Linked lists data structures to store a text. Chaining
techniques are used to store the lines of the text in which a word appears. Each node of the binary search
tree contains four fields :
(i) Word
(ii) A pointer pointing to all the lines word appears in
(iii) A pointer pointing to the subtree(left) containing all the words that appears in the text and are
predecessors of word in lexicographic order.
(iv) A pointer pointing to the subtree(right) containing all the words that appears in the text and are
successors of word in lexicographic order.
Given the following incomplete Java classes BinSrchTreeWordNode, TreeText, you are asked to complete
three methods, InsertionBinSrchTree, CreateBinSrchTree and LinesWordInBinSrchTree. For
simplicity we assume that the text is stored in a 2D array, a row of the array represents a line of the text.
Each element in the single linked list is represented by a LineNode that contains a field Line which represents a line in which the word appears, a field next which contains the address of a LineNode representing the next line in which the word appears.
public class TreeText{
BinSrchTreeWordNode RootText = null;// pointer to the root of the tree
String TextID; // Text Identification
TreeText(String tID){TextID = tID;}
void CreateBinSrchTree (TEXT text){...}
void LinesWordInBinSrchTree(BinSrchTreeWordNode Node){...}
public static void main(String[] args)
TEXT univ = new TEXT(6,4);
univ.textcont[0][0] = "Ukzn"; univ.textcont[0][1] ="Uct";
univ.textcont[0][2] ="Wits";univ.textcont[0][3] ="Rhodes";
univ.textcont[1][0] = "stellenbosch";
univ.textcont[1][1] ="FreeState";
univ.textcont[1][2] ="Johannesburg";
univ.textcont[1][3] = "Pretoria" ;
univ.textcont[2][0] ="Zululand";univ.textcont[2][1] ="NorthWest";
univ.textcont[2][2] ="Limpopo";univ.textcont[2][3] ="Wsu";
univ.textcont[3][0] ="NorthWest";univ.textcont[3][1] ="Limpopo";
univ.textcont[3][2] ="Uct";univ.textcont[3][3] ="Ukzn";
univ.textcont[4][0] ="Mit";univ.textcont[4][1] ="Havard";
univ.textcont[4][2] ="Michigan";univ.textcont[4][3] ="Juissieu";
univ.textcont[5][0] ="Cut";univ.textcont[5][1] ="Nmmu";
univ.textcont[5][2] ="ManTech";univ.textcont[5][3] ="Oxford";
// create a binary search tree (universities)
// and insert words of text univ in it
TreeText universities = new TreeText("Universities");
universities.CreateBinSrchTree(univ);
// List words Universities trees with their lines of appearance
System.out.println();
System.out.println(universities.TextID);
System.out.println();
universities.LinesWordInBinSrchTree(universities.RootText);
public class BinSrchTreeWordNode {
BinSrchTreeWordNode LeftTree = null; // precedent words
String word;
LineNode NextLineNode = null; // next line in
// which word appears
BinSrchTreeWordNode RightTree = null; // following words
BinSrchTreeWordNode(String WordValue)
{word = WordValue;} // creates a new node
BinSrchTreeWordNode InsertionBinSrchTree
(String w, int line, BinSrchTreeWordNode bst)
public class LineNode{
int Line; // line in which the word appears
LineNode next = null;
public class TEXT{
int NBRLINES ; // number of lines
int NBRCOLS; // number of columns
String [][] textcont; // text content
TEXT(int nl, int nc){textcont = new String[nl][nc];}
The method InsertionBinSrchTree inserts a word (w) in the Binary search tree. The method Create-
BinSrchTree creates a binary search tree by repeated calls to InsertionBinSrchTree to insert elements
of text. The method LinesWordInBinSrchTree traverses the Binary search tree inorder and displays the
words with the lines in which each appears.
>>>>>>>>>>>>>>>>>>>>>>
//InsertionBinTree is of type BinSearchTreeWordNode
BinSrchTreeWordNode InsertionBinSrchTree(String w, int line, BinSrchTreeWordNode bst)
//First a check must be made to make sure that we are not trying to //insert a word into an empty tree. If tree is empty we just create a //new node.
If (bst == NULL)
System.out.println(Tree was empty)
For (int rows =0; rows <= 6; rows++)
For (int cols = 0; cols <= 4; cols++)
Textcont[i][j] = wWhat is the purpose of this thread? You are yet to ask a question... Such a waste of time...
For future reference use CODE TAGS when posting code in a thread.
But again have a think about how to convey a question to others instead of blabbering on about nothing.
i think it does not get any harder than this.What is so difficult to understand. Google an implementation of a binary tree using a single array. Then you can integrate this into the required 2-dimension array for your linked list implemented as an array in your 2-d array.
Mel -
MORE A CRY FOR HELP THEN A QUESTION-THANKS!
I'm having some diffucilites debugging errors produced by my binary search tree class. Spent alot of time trying correct them but just doesn't seem to be working for me :|!. I'm working with two main classes BinaryNode and BinarySearchTree.
class BinaryNode<AnyType> extends BinarySearchTree
// Constructor
BinaryNode(AnyType theElement)
element = theElement;
left = right = null;
// Data; accessible by other package routines
AnyType element; // The data in the node
BinaryNode<AnyType> left; // Left child
BinaryNode<AnyType> right; // Right child
public class BinarySearchTree<AnyType extends Comparable<? super AnyType>>
/** The tree root. */
protected BinaryNode<AnyType> root;
private int[] unsorted = new int[] {3,6,7,2,1};
* Construct the tree.
public BinarySearchTree()
root = null;
* Insert into the tree.
* @param x the item to insert.
* @throws DuplicateItemException if x is already present.
public void insert(AnyType x)
root = insert(x, root);
* Remove from the tree..
* @param x the item to remove.
* @throws ItemNotFoundException if x is not found.
public void remove(AnyType x)
root = remove(x, root);
* Remove minimum item from the tree.
* @throws ItemNotFoundException if tree is empty.
public void removeMin()
root = removeMin(root);
* Find the smallest item in the tree.
* @return smallest item or null if empty.
public BinaryNode<AnyType> findMin()
//uses a helpler method that iterates over the left hand of the binary tree
return(findMin(root));
* Find the largest item in the tree.
* @return the largest item or null if empty.
public BinaryNode<AnyType> findMax()
return (findMax(root));
* Find an item in the tree.
* @param x the item to search for.
* @return the matching item or null if not found.
public AnyType find(AnyType x)
return elementAt(find(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;
* Internal method to get element field.
* @param t the node.
* @return the element field or null if t is null.
public AnyType elementAt(BinaryNode<AnyType> t)
return t == null ? null : t.element;
* Internal method to insert into a subtree.
* @param x the item to insert.
* @param t the node that roots the tree.
* @return the new root.
* @throws DuplicateItemException if x is already present.
protected BinaryNode<AnyType> insert(AnyType x, BinaryNode<AnyType> t)
if(t == null) {
t = new BinaryNode<AnyType>(x);
else if(x.compareTo(t.element) < 0) {
t.left = insert(x, t.left);
else if(x.compareTo(t.element) > 0 ) {
t.right = insert(x, t.right);
else {
throw new DuplicateItemException(x.toString()); // Duplicate
return t;
* 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.
* @throws ItemNotFoundException if x is not found.
protected BinaryNode<AnyType> remove(AnyType x, BinaryNode<AnyType> t)
if(t == null) {
throw new ItemNotFoundException(x.toString());
if(x.compareTo(t.element) < 0) {
t.left = remove(x,t.left);
else if(x.compareTo(t.element) > 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 = removeMin(t.right);
else {
t = (t.left != null) ? t.left : t.right;
return t;
* Internal method to remove minimum item from a subtree.
* @param t the node that roots the tree.
* @return the new root.
* @throws ItemNotFoundException if t is empty.
protected BinaryNode<AnyType> removeMin(BinaryNode<AnyType> t)
if(t == null) {
throw new ItemNotFoundException();
else if(t.left != null) {
t.left = removeMin(t.left);
return t;
else {
return t.right;
* Given a non-empty binary search tree,
* return the minimum data value found in that tree.
* Note that the entire tree does not need to be searched.
* @param t the node that roots the tree.
* @return node containing the smallest item.
protected BinaryNode<AnyType> findMin(BinaryNode<AnyType> t)
if(t != null) {
while(t.left != null) {
t = t.left;
return t; //the smallest value
* Internal method to find the largest item in a subtree.
* @param t the node that roots the tree.
* @return node containing the largest item.
protected BinaryNode<AnyType> findMax(BinaryNode<AnyType> t)
if(t != null) {
while(t.right != null) {
t = t.right;
return t; //the largest value
* Internal method to find an item in a subtree.
* @param x is item to search for.
* @param t the node that roots the tree.
* @return node containing the matched item.
private BinaryNode<AnyType> find(AnyType x, BinaryNode<AnyType> t)
while(t != null) {
if(x.compareTo(t.element) < 0) {
t = t.left;
else if(x.compareTo(t.element) > 0) {
t = t.right;
else {
return t; // Match
return null; // Not found
public void betweenTraverse() {
betweenTraverse(root);
* Given two integers,
* print all the values in the tree which are between these two numbers
* in ascending order.
* @param t is BinaryTree to search through
* @param a is min integer to start print from
* @param b is max integer to keep integer print between
private void betweenTraverse(BinaryNode<AnyType> t)
//enter samllest vaule
int a = System.in.read();
//enter largetest vaule
int b = System.in.read();
if (t != null) {
inorderTraverse(t.left);
if(t.elementAt(t) >a && t.elementAt(t) < b) { //LINE 274 with error
System.out.println(t.elementAt(t));
inorderTraverse(t.right);
* Given an array of unsorted integers
* adds add the these elements of unsorted as nodes
* to an initially empty binary search tree
* @param x is array which it element to be added to a binary tree
public BinarySearchTree<Integer> numberstoTree(int[] x)
BinarySearchTree<Integer> treeOne = new BinarySearchTree<Integer>();
Arrays.sort(x);
for (int i = 0 ; i < x.length ; i++) {
int j = x;
treeOne.insert(j);
treeOne.inorderTraverse();
return treeOne;
public void inorderTraverse() {
inorderTraverse(root);
private void inorderTraverse(BinaryNode<AnyType> t) {
if (t != null) {
inorderTraverse(t.left);
System.out.println(t.elementAt(t));
inorderTraverse(t.right);
// Test program
public static void main(String[] args)
BinarySearchTree<Integer> t = new BinarySearchTree<Integer>();
final int NUMS = 4000;
final int GAP = 37;
System.out.println("Checking... (no more output means success)");
for( int i = GAP; i != 0; i = ( i + GAP ) % NUMS ) {
t.insert(i);
for(int i = 1; i < NUMS; i += 2) {
t.remove(i);
if(t.findMin().elementAt(t) != 2 || t.findMax().elementAt(t) != NUMS - 2) { //LINE 332 with error
System.out.println("FindMin or FindMax error!");
for(int i = 2; i < NUMS; i += 2) {
if( t.find(i) != i) {
System.out.println("Find error1!");
for(int i = 1; i < NUMS; i += 2) {
if(t.find(i) != null) {
System.out.println("Find error2!");
}I getting these errors:BinarySearchTree.java:274: operator > cannot be applied to java.lang.Comparable,int
if(t.elementAt(t) >a && t.elementAt(t) < b) {
^
BinarySearchTree.java:274: operator < cannot be applied to java.lang.Comparable,int
if(t.elementAt(t) >a && t.elementAt(t) < b) {
^
BinarySearchTree.java:332: elementAt(BinaryNode) in BinarySearchTree cannot be applied to (BinarySearchTree<java.lang.Integer>)
if(t.findMin().elementAt(t) != 2 || t.findMax().elementAt(t) != NUMS - 2) {
^
BinarySearchTree.java:332: cannot find symbol
symbol : method elementAt(BinarySearchTree<java.lang.Integer>)
location: class java.lang.Integer
if(t.findMin().elementAt(t) != 2 || t.findMax().elementAt(t) != NUMS - 2) {
^ I've tried to change the method return types, to integer, AnyType but still producing more or same amount of errors, any help debugging this would be so helpful!.
ThanksSo i've tried to re implement the static statements. i.e
if(t.findMin().compareTo(t.elementAt(t.root)) != 2 || t.findMax().compareTo(t.elementAt(t.root)) != NUMS - 2) {
System.out.println("FindMin or FindMax error!");
}but now receiving this error :
BinarySearchTree.java: operator > cannot be applied to java.lang.Comparable,java.lang.Integer
if(t.elementAt(t) > A && t.elementAt(t) < B) { //LINE 274 WITH ERROR
^
BinarySearchTree.java: operator < cannot be applied to java.lang.Comparable,java.lang.Integer
if(t.elementAt(t) > A && t.elementAt(t) < B) { //LINE 274 WITH ERROR
^
BinarySearchTree.java: cannot find symbol
symbol : method compareTo(java.lang.Integer)
location: class BinaryNode<java.lang.Integer>
if(t.findMin().compareTo(t.elementAt(t.root)) != 2 || t.findMax().compareTo(t.elementAt(t.root)) != NUMS - 2) {
^
BinarySearchTree.java: cannot find symbol
symbol : method compareTo(java.lang.Integer)
location: class BinaryNode<java.lang.Integer>
if(t.findMin().compareTo(t.elementAt(t.root)) != 2 || t.findMax().compareTo(t.elementAt(t.root)) != NUMS - 2) {The method compareTo takes an object as defined in the comparable interface which my BinarySearchTree extends. Binary Node is a child of BinarySearchTree. I've been messing around with where i initiate the compareTo method but not had any success, any idea/push in the right direction would be appreciated.
Thanks -
How many different binary search trees can store the keys {1,2,3}
I am having a hard time answering this question:
How many different binary search trees can store the keys {1,2,3} or how about {1,2,3,4} and how did u figure this out?
Any responses helpful
Thanks!the.maltese.falcon wrote:
practissum, shame on you for doing this chap's homework for him. @ the OP, this is a Java forum, not a basic data structures forum.
Also, you forgot the cases
3
1
2and
1
3
2
the.maltese.falcon, I was just trying to help him get started with the base case. Notice that I didn't enumerate all of the possibilities, but was trying to help the OP get on the right track. You, however, have done this. So shame to you, sir! -
Searching a binary search tree written to a file
hello
I have a binary search tree which has 10 levels. Now I want to search a node
after writing all the nodes to a file.
Can anyone help me in doing this. A sample code would be great ...
Thanks
KYou suggest that I do away with the inner class
then?Absolutely. In fact I strongly suggest this. You are learning how to code and need to do things cleanly and in small steps. That means first creating your Node class and making sure it works. Then creating your Tree class, and making sure it works. In fact I would load the Strings into the Tree class first directly and testing things before even thinking about reading to and from files. Only then should you implement the file input and output steps.
The key here is that you don't go on to the next step until you're reasonably sure that your current code works. Remember, it's MUCH easier to code than to debug. -
Binary search tree - writing to a file in alphabetic order words from tree
Hi
I have written a program that will read a list of words from a file, insert these into a binary search tree, write words from the tree to another file, so that the resulting list contains words in ascending order. My input file Alpha1.txt contains the following contents in the order and format given (one word per line):
Dawn
Dave
Mike
Beth
David
Gina
Pat
Cindy
Sue
My program is supposed to be producing an alphabetical list of these words in another file "final.txt".
Instead it gives me the following list:
Dave Beth David Gina Cindy Sue Pat Mike Dawn
This is obviously wrong, right? My correct list in "final.txt" should be
Beth Cindy Dave David Dawn Gina Mike Pat Sue
I am not sure what is wrong with my code which I reproduce below:
import java.io.*;
import java.util.*;
//read Java Developer's Almanac from exampledepot.com
//Read this: http://en.wikipedia.org/wiki/Tree_traversal
/**preorder(node)
print node.value
if node.left ? null then preorder(node.left)
if node.right ? null then preorder(node.right)
public class AlphabeticBinarySortTree
private static TreeNode root;
private static TreeNode runner;
static String[] alphaArray;
static int alphaCounter;
private static TreeNode alphaRunner;
//Inner class
private static class TreeNode
String word;
TreeNode left;
TreeNode right;
int count;
public TreeNode(String word)
this.word = word;
left = null;
right = null;
public void insertAll(TreeNode newNode)
if(newNode.word.compareTo(runner.word) < 1)
System.out.println("newNode.word = " + newNode.word);
if(runner.left == null)
runner.left = newNode;
runner = runner.left;
else
insertAll(newNode);
else if(newNode.word.compareTo(runner.word) > 1)
System.out.println("newNode.word = " + newNode.word);
if(runner.right == null)
runner.right = newNode;
runner = runner.right;
else
insertAll(newNode);
else
count++;
}// end method insertAll
// Recursively print words (with counts) in sorted order
public static void printInPreOrder(TreeNode root)
System.out.println(root.word + " ");
if(root.left != null)
printInPreOrder(root.left);
if(root.right != null)
printInPreOrder(root.right);
} //end method printInPreOrder()
//called from inside main
public static void arrangeInAscendingOrder(TreeNode root, PrintWriter pWriter)
if(root.left != null)
arrangeInAscendingOrder(root.left, pWriter);
System.out.println();
System.out.println();
System.out.println(root.word + " ");
pWriter.write(root.word + " ");
if(root.right != null)
arrangeInAscendingOrder(root.right, pWriter);
}//end inner class TreeNode
public AlphabeticBinarySortTree()
root = null;
//belong to the outer class
public static void main(String[] args)
System.out.println("This program reads text from a file that it will parse. ");
System.out.println("In doing so, it will eliminate duplicate strings and ");
System.out.println("pick up only unique strings.These strings will be in a ");
System.out.println("stored in alphabetical order in a binary Search tree before they are ");
System.out.println("written out to another text file in alphabetic order");
//open the file for reading
try
BufferedReader bReader = new BufferedReader(new FileReader("Alpha1.txt"));
String words;
int count;
//System.out.println("A test to inspect the contents of words: " + words);
//System.out.println("Words =" + words);
count = 0;
//why is there an endless loop when
//I use "while(str != null)
StringTokenizer st;
st = null;
//based on http://www.exampledepot.com/egs/java.io/ReadLinesFromFile.html
while ((words = bReader.readLine()) != null)
st = new StringTokenizer(words);
while(st.hasMoreTokens())
//shiffman.net/teaching/a2z/concordance
String token = st.nextToken();
System.out.println("Token = " +token);
AlphabeticBinarySortTree.initiateInsert(token);
//count the number of tokens in the string
count++;
}//end inner while
}//end outer while
System.out.println("Here are the contents of your tree:");
//System.out.println("before the call to print()");
print();
System.out.println("the no of words in the file is: " + count);
bReader.close();
}//end of try
catch(IOException exception)
exception.printStackTrace();
/**try
FileWriter fWriter = new FileWriter("final.txt");
BufferedWriter bWriter = new BufferedWriter(fWriter);
PrintWriter pWriter = new PrintWriter(bWriter);
catch(IOExcepion exception)
exception.printStackTrace();
} // end main here
//this method belongs to the outer class
static void initiateInsert(String word)
//TreeNode is also static by the way
TreeNode newNode = new TreeNode(word);
if(root == null)
root = newNode;
System.out.println("root.word = " + root.word);
runner = root;
else
runner.insertAll(newNode);
// Start the recursive traversing of the tree
//without the access specifier 'static'
//I would get the following error message
//AlphabeticBinarySortTree.java:119: non-static method print() cannot be referenced from a static context
public static void print()
//System.out.println("**********AM I INSIDE THE PRINT() METHOD? ********");
if (root != null)
//System.out.println("++++++++ AM I INSIDE THE IF BLOCK OF THE PRINT() METHOD? +++++++");
//System.out.println("Inside THE IF BLOCK OF print() BUT BEFORE THE CALL TO printInPreOrder(),root.word = " + root.word);
AlphabeticBinarySortTree.TreeNode.printInPreOrder(root);
//open the file for writing
try
FileWriter fWriter = new FileWriter("final.txt");
BufferedWriter bWriter = new BufferedWriter(fWriter);
PrintWriter pWriter = new PrintWriter(bWriter);
AlphabeticBinarySortTree.TreeNode.arrangeInAscendingOrder(root, pWriter);
pWriter.close();
catch(IOException eException)
eException.printStackTrace();
}//end of if block
} // end of method print
}//end outer enclosing class here--------
All help is highly appreciated. Thanks for your time and consideration.You suggest that I do away with the inner class
then?Absolutely. In fact I strongly suggest this. You are learning how to code and need to do things cleanly and in small steps. That means first creating your Node class and making sure it works. Then creating your Tree class, and making sure it works. In fact I would load the Strings into the Tree class first directly and testing things before even thinking about reading to and from files. Only then should you implement the file input and output steps.
The key here is that you don't go on to the next step until you're reasonably sure that your current code works. Remember, it's MUCH easier to code than to debug. -
Problem with binary search tree
Hi all, just having troubles with a program im writing.
My program is based on a binary search tree full of items which are passed in via an input file and then saved to an output file.
I have written a sellItem method which gets passed in the item and quantity that has been sold which then needs to be changed in the binary tree.
Here if my sell Item method:
public void sellItem(Item item, int quantity){
stockItem = item;
mQuantity = quantity;
if (tree.includes(stockItem)){
int tempQuantity = stockItem.getQuantityInStock();
tempQuantity -= mQuantity;
else{
throw new IllegalArgumentException("The Barcode " + mBarCode + " does NOT exist.");
}and here is where i am calling it in a test class :
number1.sellItem(item1, 40);Each item is in this format :
ABCD, PENCIL, 1, 0.35, 200, 100, 200
where 200 is the quantity.
Therefore if i pass 40 into the method the binary search tree should then store the quantity as 160.
below is a copy of my binary tree :
public class BSTree extends Object {
private class TreeNode extends Object{
public Comparable data;
public TreeNode left;
public TreeNode right;
public TreeNode() {
this(null);
public TreeNode(Comparable barCode){
super();
data = barCode;
left = null;
right = null;
private TreeNode root;
private int nodeCount;
public BSTree(){
super();
root = null;
nodeCount = 0;
public boolean isEmpty() {
return root == null;
public int size() {
return nodeCount;
private TreeNode attach(TreeNode newPointer, TreeNode pointer){
if (pointer == null){
nodeCount++;
return newPointer;
else {
Comparable obj1 = (Comparable) newPointer.data;
Comparable obj2 = (Comparable) pointer.data;
if (obj1.compareTo(obj2) < 0) //Go left
pointer.left = attach(newPointer, pointer.left);
else //Go right
pointer.right = attach(newPointer, pointer.right);
return pointer;
public void insert(Comparable item){
//Create a new node and initialize
TreeNode newPointer = new TreeNode(item);
//Attach it to the tree
root = attach(newPointer, root);
public Comparable remove(Comparable key) {
TreeNode pointer;
TreeNode parent;
//Find the node to be removed
parent = null;
pointer = root;
while ((pointer != null) && !key.equals(pointer.data)) {
parent = pointer;
if (key.compareTo(pointer.data) <0)
pointer = pointer.left;
else
pointer = pointer.right;
if (pointer == null)
return null;
//Orphans
TreeNode leftSubtree = pointer.left;
TreeNode rightSubtree = pointer.right;
if (parent == null)
root = null;
else if (key.compareTo(parent.data) < 0)
parent.left = null;
else
parent.right = null;
//Reattaching any orphans in the left subtree
if (leftSubtree != null) {
root = attach(leftSubtree, root);
nodeCount--;
//Reattaching any orphans in the right subtree
if (rightSubtree != null) {
root = attach(rightSubtree, root);
nodeCount--;
nodeCount--;
return pointer.data;
private TreeNode search(TreeNode pointer, Comparable key) {
if (pointer == null)
return null;
else if (pointer.data.compareTo(key) == 0)
return pointer;
else if (key.compareTo(pointer.data) < 0)
return search(pointer.left, key);
else
return search(pointer.right, key);
public boolean includes(Comparable key) {
return (search(root, key) != null);
public Comparable retrieve(Comparable key) {
TreeNode pointer;
pointer = search(root, key);
if (pointer == null)
return null;
else
return pointer.data;
public Comparable[] getAllInOrder() {
Comparable[] list = new Comparable[nodeCount];
inOrderVisit(root,list,0);
return list;
private int inOrderVisit(TreeNode pointer, Comparable[] list, int count) {
if (pointer != null) {
count = inOrderVisit(pointer.left, list, count);
list[count++] = pointer.data;
count = inOrderVisit(pointer.right, list, count);
return count;
public String toString() {
StringBuffer result = new StringBuffer(100);
inOrderString(root, result);
return result.toString();
private void inOrderString(TreeNode pointer, StringBuffer result) {
if (pointer != null) {
inOrderString(pointer.left, result);
result.append(pointer.data.toString() + "\n");
inOrderString(pointer.right, result);
}Thanks for everyones help. Keep in mind i'm very new to java.Hi all, just having troubles with a program im writing.
My program is based on a binary search tree full of items which are passed in via an input file and then saved to an output file.
I have written a sellItem method which gets passed in the item and quantity that has been sold which then needs to be changed in the binary tree.
Here if my sell Item method:
public void sellItem(Item item, int quantity){
stockItem = item;
mQuantity = quantity;
if (tree.includes(stockItem)){
int tempQuantity = stockItem.getQuantityInStock();
tempQuantity -= mQuantity;
else{
throw new IllegalArgumentException("The Barcode " + mBarCode + " does NOT exist.");
}and here is where i am calling it in a test class :
number1.sellItem(item1, 40);Each item is in this format :
ABCD, PENCIL, 1, 0.35, 200, 100, 200
where 200 is the quantity.
Therefore if i pass 40 into the method the binary search tree should then store the quantity as 160.
below is a copy of my binary tree :
public class BSTree extends Object {
private class TreeNode extends Object{
public Comparable data;
public TreeNode left;
public TreeNode right;
public TreeNode() {
this(null);
public TreeNode(Comparable barCode){
super();
data = barCode;
left = null;
right = null;
private TreeNode root;
private int nodeCount;
public BSTree(){
super();
root = null;
nodeCount = 0;
public boolean isEmpty() {
return root == null;
public int size() {
return nodeCount;
private TreeNode attach(TreeNode newPointer, TreeNode pointer){
if (pointer == null){
nodeCount++;
return newPointer;
else {
Comparable obj1 = (Comparable) newPointer.data;
Comparable obj2 = (Comparable) pointer.data;
if (obj1.compareTo(obj2) < 0) //Go left
pointer.left = attach(newPointer, pointer.left);
else //Go right
pointer.right = attach(newPointer, pointer.right);
return pointer;
public void insert(Comparable item){
//Create a new node and initialize
TreeNode newPointer = new TreeNode(item);
//Attach it to the tree
root = attach(newPointer, root);
public Comparable remove(Comparable key) {
TreeNode pointer;
TreeNode parent;
//Find the node to be removed
parent = null;
pointer = root;
while ((pointer != null) && !key.equals(pointer.data)) {
parent = pointer;
if (key.compareTo(pointer.data) <0)
pointer = pointer.left;
else
pointer = pointer.right;
if (pointer == null)
return null;
//Orphans
TreeNode leftSubtree = pointer.left;
TreeNode rightSubtree = pointer.right;
if (parent == null)
root = null;
else if (key.compareTo(parent.data) < 0)
parent.left = null;
else
parent.right = null;
//Reattaching any orphans in the left subtree
if (leftSubtree != null) {
root = attach(leftSubtree, root);
nodeCount--;
//Reattaching any orphans in the right subtree
if (rightSubtree != null) {
root = attach(rightSubtree, root);
nodeCount--;
nodeCount--;
return pointer.data;
private TreeNode search(TreeNode pointer, Comparable key) {
if (pointer == null)
return null;
else if (pointer.data.compareTo(key) == 0)
return pointer;
else if (key.compareTo(pointer.data) < 0)
return search(pointer.left, key);
else
return search(pointer.right, key);
public boolean includes(Comparable key) {
return (search(root, key) != null);
public Comparable retrieve(Comparable key) {
TreeNode pointer;
pointer = search(root, key);
if (pointer == null)
return null;
else
return pointer.data;
public Comparable[] getAllInOrder() {
Comparable[] list = new Comparable[nodeCount];
inOrderVisit(root,list,0);
return list;
private int inOrderVisit(TreeNode pointer, Comparable[] list, int count) {
if (pointer != null) {
count = inOrderVisit(pointer.left, list, count);
list[count++] = pointer.data;
count = inOrderVisit(pointer.right, list, count);
return count;
public String toString() {
StringBuffer result = new StringBuffer(100);
inOrderString(root, result);
return result.toString();
private void inOrderString(TreeNode pointer, StringBuffer result) {
if (pointer != null) {
inOrderString(pointer.left, result);
result.append(pointer.data.toString() + "\n");
inOrderString(pointer.right, result);
}Thanks for everyones help. Keep in mind i'm very new to java. -
Binary search tree help...
Ok, maybe someone can help me with this one. Here's the code that I'm having trouble with:
public Object findValue(Comparable aKey)
Node result = (Node) findByKey(aKey);
if(result != null && result.getNodeKey() == aKey)
return result.getNodeData();
else
return null;
}The problem is in the condition for the if statement, particularly, "result.getNodeKey() == aKey". I've checked both values for result.getNodeKey() and aKey, and they are both the same, but the program gives ma a false result, which sends it straight to the "return null;" statement. Any thoughts as to why it might do this?I just found another trouble spot. Here's the code this time:
public boolean delete(Comparable aKey)
Node result = (Node) findByKey(aKey);
if(result != null && result.getNodeKey().equals(aKey))
Node currentNode = rootNode;
Node parentNode = null;
boolean found = false;
while(!found && currentNode != null)
if(aKey.compareTo(currentNode.getNodeKey()) < 0)
parentNode = currentNode;
currentNode = (Node)currentNode.getLeftChild();
else
if(aKey.compareTo(currentNode.getNodeKey()) > 0)
parentNode = currentNode;
currentNode = (Node) currentNode.getRightChild();
else
found = true;
if (parentNode == null)
//here's where I need assistance
return true;
else
parentNode.setLeftChild((Node) currentNode.getLeftChild());
Node holderNode = (Node) currentNode.getLeftChild();
holderNode.setRightChild((Node) currentNode.getRightChild());
return true;
else
return false;
}I'm trying to delete from the binary search tree, and I'm not sure how to adjust for deleting the top of the tree (rootNode, in this case) before the rest of the tree is gone. Any ideas? -
Hello,
I'm working on a BinarySearchTree and I am looking for a little bit of advice for my find method or overall optimization comments. For some reason when I set 'found' = null at the beginning of the method I am getting nullpointer exception. But, if I put it in the else statement, it never gets executed. As you can see, find is recursive function. Any help or advice would be greatly appreciated. Thanks in advance!!!!!
* All items are ordered so that all items in the left subtree are smaller
* than the item in the root and all items in the right subtree are larger
* than the item in the root. This is true for all nodes in the tree.
* No duplicates are allowed.
* This tree is specific to the doctor's office application and therefore
* contains Procedure objects - it is expected that Procedure objects are
* comparable.
public class BinarySearchTree {
* The item stored in the root of this BinarySearchTree
private Procedure value;
* The parent of this BinarySearchTree
private BinarySearchTree parent;
* The left child of this BinarySearchTree
return found;
* Print the values of all the nodes of the BinarySearchTree rooted
* at this node in infix order, one value per line.
public void inOrder() {
if ( leftChild != null ) {
leftChild.inOrder();
System.out.println( value.toString() );
if ( rightChild != null ) {
rightChild.inOrder();
} // BinarySearchTree */
private BinarySearchTree leftChild;
* The right child of this BinarySearchTree
private BinarySearchTree rightChild;
* A constructor used for the first node in the tree.
* There is no parent.
* @param item The value to be stored at this node of the tree.
public BinarySearchTree( Procedure item ) {
value = item;
leftChild = null;
rightChild = null;
* Accessor function for the value at this node
* @return the value at this node.
public Procedure getValue() {
return value;
* Accessor function for the parent of this node.
* @return the parent of this node.
public BinarySearchTree getParent() {
return parent;
* Accessor function for the left child of this node.
* It allows me to move to the left child.
* @return the left child of this node.
public BinarySearchTree getLeftChild() {
return leftChild;
* Accessor function for the right child of this node.
* It allows me to move to the right child.
* @return the right child of this node.
public BinarySearchTree getRightChild() {
return rightChild;
* Change the left child of this node.
* @param newLeft the new left child
private void setLeftChild( BinarySearchTree newLeft ) {
return found;
* Print the values of all the nodes of the BinarySearchTree rooted
* at this node in infix order, one value per line.
public void inOrder() {
if ( leftChild != null ) {
leftChild.inOrder();
System.out.println( value.toString() );
if ( rightChild != null ) {
rightChild.inOrder();
} // BinarySearchTree leftChild = newLeft;
leftChild.setParent( this );
* Change the right child of this node.
* @param newRight the new right child
private void setRightChild( BinarySearchTree newRight ) {
rightChild = newRight;
rightChild.setParent( this );
* Change the parent of this node.
* @param newParent the new parent
return found;
* Print the values of all the nodes of the BinarySearchTree rooted
* at this node in infix order, one value per line.
public void inOrder() {
if ( leftChild != null ) {
leftChild.inOrder();
System.out.println( value.toString() );
if ( rightChild != null ) {
rightChild.inOrder();
} // BinarySearchTree
private void setParent( BinarySearchTree newParent ) {
parent = newParent;
* Add a new item to the tree. If the item is smaller than
* the value stored at the root node, find a place for it in
* the left subtree.
* @param item the item to be added to the tree.
public void add( Procedure item ){
BinarySearchTree curNode = this;
if ( item.compareTo( value ) == 0 ) {
System.err.println( "Can't have duplicate items in the tree" );
} else if ( item.compareTo( value ) < 0 ) {
if ( leftChild != null ) {
curNode = leftChild;
curNode.add( item );
} else {
curNode.setLeftChild( new BinarySearchTree( item ) );
} else if ( item.compareTo( value ) > 0 ) {
if ( rightChild != null ) {
curNode = rightChild;
curNode.add( item );
} else {
curNode.setRightChild( new BinarySearchTree( item ) );
* Is the Procedure named in the parameter in the tree? Case is
* ignored when doing the comparison. If the Procedure is found,
* return it. If not, print a message and return null.
* The purpose of the message is for you to KNOW that an item was
* not found in the tree. Use the format:
* 'item' not found in the binary search tree
* where item is the name of the procedure that you are looking for.
* @param item The item to look for
public Procedure find( String item ) {
BinarySearchTree curNode = this;
//???????blows up when I set it to null here
Procedure found = null;
if ( item.compareToIgnoreCase( value.getName() ) == 0 ) {
found = value;
System.out.println("**********************************"
+ "***************************found it");
else if ( item.compareToIgnoreCase( value.getName() ) < 0 ) {
if ( leftChild != null ) {
System.out.println("LLLLLLLLLLLLLLLLLLLLLLLLLLLLLL");
curNode = leftChild;
curNode.find( item );
} else if ( item.compareToIgnoreCase( value.getName() ) > 0 ) {
if ( rightChild != null ) {
System.out.println("RRRRRRRRRRRRRRRRRRRRRRRRRRRRR");
curNode = rightChild;
curNode.find( item );
//??????NEVER GETS EXECUTED WHEN I UNCOMMENT THIS OUT!!!
// else {
// found = null;
// System.err.println( item
// + "7777777777777777777777777777777777777777not found in the binary search tree");
return found;
* Print the values of all the nodes of the BinarySearchTree rooted
* at this node in infix order, one value per line.
public void inOrder() {
if ( leftChild != null ) {
leftChild.inOrder();
System.out.println( value.toString() );
if ( rightChild != null ) {
rightChild.inOrder();
} // BinarySearchTreeFor some reason when I set 'found' = null at the
beginning of the method I am getting nullpointer
exception.That must come from outside find() method since nothing in find() uses the value of the "found" variable.
But, if I put it in the else statement, it never
gets executed.That's because your if-else-else already considers all the possible cases -- the value that compareToIgnoreCase returns is either equal to, less than, or greater than 0. It can never be anything else.
You only assign to the local variable "found" if the searched item was found immediately from the 'current node' (= the root); if the item was in the left or right subtree you are happily ignoring it. You needfound = curNode.find( item );in both of the else-cases.
The item is "not found" when it should be in the left/right child by the comparison test, but the left/right child is empty. So the find() method needs this, and the same for the left childif (compare to > 0) {
if ( rightChild != null ) {
// find from child
} else {
// not found from tree at all
}The "not found" code would have to be duplicated, so you should refactor the conditions...Here's a possibility: if ( item is value ) {
// found it in the current node
else if (item is less than value and leftChild is not null) {
// try to find it in the left child
else if (item is greater than value and rightChild is not null) {
// try to find it in the right child
else {
// should be in right/left child but
// it's empty --- not found!
}
Maybe you are looking for
-
I have a problem with Exchange and extracting out attachments. from email. We use Exchange 2007 server and https connection. Https connection works well, but I can't get attachments. Program stops at tag --> cfexchangemail action="getAttachments" wit
-
Getting error while Using BAPI Interface in VB
Hi, I m getting error message while creating object of SAP.BAPI.1 Error message is "out of memory : run time error 7". do I need to install any patch to my local PC? If yes then from where could i get that patch. Plz help me out. Thanks & Regards, Sa
-
Song dissapeared from my iPhone and iTunes account
I recently purchased an Album for my kids (Madagascar 2) and have been listening to it near daily on my iPhone. There is one song in particular that they love (The Traveling Song) that could only be purchased by buying the entire album. For some reas
-
I can't believe it's taking this long to get my PDF. I filed some this morning, and in the early afternoon i reached someone from Adobe who assured me they are aware of the problem and are working to resolve it. He suggested I wait another hour and t
-
Been watching HD TV shows over home WI-FI from remote desktop using Apple TV for a month with my 1080i TV. Tonight getting error on TV, even on recently watched shows, "This content requires HDCP for playback. Either your HDMI cable isn't properly co