Need to search Tree
I am looking for some pointers towards implementing search functionality in Tree.
I am using Jdev 11g. I have implemented a Tree structure on one my pages.
This Tree structure is pretty huge and confusing to user at times.
I want to implement a search functionality over this existing tree which filters and expands tree structure based on search criteria.
any pointers towards it would be helpful
Thanks in advance.
Hi,
the way to do this is through recursive search. Below is a coarse grain outline
JUCtrlHierBinding treeBinding = --- get access to the tree binding defined in the PageDef ----
String searchAttributeArray[] = --- build and array of search attributes to look into (attributes on the tree binding) ---
//Define a node to search in. In this example, the root node is used as
//the starting point
JUCtrlHierNodeBinding root = treeBinding.getRootNodeBinding();
//Retrieve the tree node keys that match the search criteria
RowKeySet resultRowKeySet =
searchTreeNode(root,searchAttributeArray,searchString);
//build the list of row sets for the full path that leads to the
//nodes that match the search condition
RowKeySet disclosedRowKeySet =
buildDiscloseRowKeySet(treeBinding,resultRowKeySet);
//expand the tree using the tree component JSF binding reference to
//display the found nodes
tree1.setSelectedRowKeys(resultRowKeySet);
tree1.setDisclosedRowKeys(disclosedRowKeySet);
//PPR the tree to show the changed disclosure state
AdfFacesContext.getCurrentInstance().addPartialTarget(tree1);
}The searchTreeNode(root,searchAttributeArray,searchString); is the recursive method that calls itself for as long as the node has chilren. The root argument is the current node to start the search from. If you find a leaf and on the way up, you check the node (which is a row) for the search condition) If the search condition is met, return the RowKeySet of the node and store it.
Frank
Similar Messages
-
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!
} -
Significant Comparisons in Binary Search Trees?
Hello,
I am a bit confused as to what constitutes a significant comparison in a binary search tree. I have an assignment where I need to modify a BST class to keep track of the number of significant comparisons being done for an analysis of running time. The class supports search, insert, and delete and the assignment stipulates that each method needs to update the number of comparisons instance variable that you implement. The comparison count is obvious for the pure recursive search, but I don't understand what to and what not to count in the delete and insert methods. Is this a standard term that is defined explicitly, or is this my professor demanding of us to think critically for better or worse? Thanks for any help.I know what a BST tree is, and I know what comparisons are, but I
don't know what 'significant comparisons' are. Maybe if you could tell
me what the difference between a significant and insignificant
comparison was I'd be in business.According to some notes on my desk, a 'significant comparison' causes
a rotation of a subtreee in a 'red-black' tree; but I don't know what it is
supposed to be in a general sorted binary tree. My guess is that this is
not a generally accepted term. I might be wrong again ...
kind regards,
Jos
ps. Hi Duffy, how are you doing? -
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 -
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. -
Searching a Binary Non-Search Tree
I'm working on a project where a binary search tree was created (sorted on employee last name). However, now the task is to find an employee based on employee ID (not last name) ... so the "search" part of the binary search tree is useless. Instead, I have to traverse the whole tree until I find the employee ID. This seems like it should be just a slight adjustment of the in-order traversal algorithm where I need to add some logic to check if the employee ID at the current node matches or not; however, I can't get it to work. Any pointers on the basic concepts involved here would be greatly appreciated. I seem to have some difficulty in designing a recursive solution. Thanks!
That's the type of algorithm I was trying to implement, but I'm evidently still doing something wrong. My algorithm just returns the first leaf it hits ... not sure what I'm doing wrong.
public Node find(int empID)
Node employee = find(empID, root);
return employee;
private Node find(int empID, Node current) //returns node of Employee or null if not found
if(current != null && current.myEmployee.getEmpNum() != empID) //keep looking through tree recursively
if(current.leftChild != null)
current = find(empID, current.leftChild);
if(current.rightChild != null)
current = find(empID, current.rightChild);
return current;
Edited by: kthomp271828 on Dec 15, 2009 12:18 PM -
Print Graphical Representation of Binary Search Tree
I need to print out a graphical representation of a binary search tree. Here is the source code I'm working with but it doesn't display the children correctly sometimes, especially with large trees.
Stack globalStack = new Stack();
globalStack.push(root);
int nBlanks = 32;
boolean isRowEmpty = false;
System.out.println("************************************************");
while (isRowEmpty == false) {
Stack localStack = new Stack();
isRowEmpty =true;
for (int i=0; i < nBlanks; i ++);
System.out.print(' ');
while (globalStack.isEmpty()==false) {
Node temp = (Node)globalStack.pop();
if (temp != null) {
System.out.print(temp.data);
localStack.push(temp.leftChild);
localStack.push(temp.rightChild);
if (temp.leftChild != null || temp.rightChild != null)
isRowEmpty = false;
} else {
System.out.print(" -- ");
localStack.push(null);
localStack.push(null);
for (int i = 0 ; i < nBlanks*2-2; i++)
System.out.print(' ');
} //end while loop isEmpty is false
System.out.println();
nBlanks /= 2;
while (localStack.isEmpty()==false)
globalStack.push (localStack.pop());
}//end while loop isRowEmpty is false
System.out.println("************************************************");
Here is an example (here the bottom children aren't aligned correctly)
4
3 20
-- -- 11 23
-- -- -- -- -- 15 -- --Well, using System.out is not really the best way for a Graphical representation...
May be java.awt.Graphics would be far better, both for the programmer and the user of your application. And please use tags when you post code, - makes it readable. -
Need to expand tree by passing treeId thr URL not by clicking manually.
Sub: Need to expand tree by passing Id thr URL.
Hi,
Here i have Library.java and ajaxTree.jsf files (collected from Jboss richfaces)
There is having a list of artist .
If u click on a particular artistname then the respective albums(with their checkboxes) will expand and show like a treenode.
just look at d url : "http://localhost:8080/richfaces-demo-3.2.1.GA/richfaces/tree.jsf?c=tree&albumIds=1001,1002,1005,1008,1009,1010&client=0"
I m passing album Ids and clientId in url browser and receiving in d Library.java.
I need to expand the required client tree to show albums without clicking on artistname rather by passing the clientId from Url.
I thnk one EventHandling class( PostbackPhaseListener.java ) is responsible for expanding but I m unable to understand.
How can I do it.
Plz help asap.
/###############ajaxTree.jsf##########Start##############/
<ui:composition xmlns="http://www.w3.org/1999/xhtml"
xmlns:ui="http://java.sun.com/jsf/facelets"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:a4j="http://richfaces.org/a4j"
xmlns:rich="http://richfaces.org/rich"
xmlns:c="http://java.sun.com/jstl/core">
<p>This tree uses "ajax" switch type, note that for collapse/expand operations it will be Ajax request to the server. You may see short delay in this case.</p>
<h:form>
<rich:tree style="width:300px" value="#{library.data}" var="item" nodeFace="#{item.type}">
<rich:treeNode type="artist" >
<h:outputText value="#{item.name}" />
</rich:treeNode>
<rich:treeNode type="album" >
<h:selectBooleanCheckbox value="#{item.selected}"/>
<h:outputText value="#{item.title}" />
</rich:treeNode>
</rich:tree>
<h:commandButton value="Update" />
</h:form>
</ui:composition>
/###############ajaxTree.jsf##########End##############/
/************************Library.java*********Start****************/
package org.richfaces.demo.tree;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.StringTokenizer;
import javax.servlet.http.HttpServletRequest;
import javax.faces.context.FacesContext;
import org.richfaces.model.TreeNode;
public class Library implements TreeNode {
private static final long serialVersionUID = -3530085227471752526L;
private Map artists = null;
private Object state1;
private Object state2;
private Map getArtists() {
if (this.artists==null) {
initData();
return this.artists;
public void addArtist(Artist artist) {
addChild(Long.toString(artist.getId()), artist);
public void addChild(Object identifier, TreeNode child) {
getArtists().put(identifier, child);
child.setParent(this);
public TreeNode getChild(Object id) {
return (TreeNode) getArtists().get(id);
public Iterator getChildren() {
return getArtists().entrySet().iterator();
public Object getData() {
return this;
public TreeNode getParent() {
return null;
public boolean isLeaf() {
return getArtists().isEmpty();
public void removeChild(Object id) {
getArtists().remove(id);
public void setData(Object data) {
public void setParent(TreeNode parent) {
public String getType() {
return "library";
private long nextId = 0;
private long getNextId() {
return nextId++;
private Map albumCache = new HashMap();
private Map artistCache = new HashMap();
private Artist getArtistByName(String name, Library library) {
Artist artist = (Artist)artistCache.get(name);
if (artist==null) {
artist = new Artist(getNextId());
artist.setName(name);
artistCache.put(name, artist);
library.addArtist(artist);
return artist;
private Album getAlbumByTitle(String title, Artist artist) {
Album album = (Album)albumCache.get(title);
if (album==null) {
album = new Album(getNextId());
album.setTitle(title);
albumCache.put(title, album);
artist.addAlbum(album);
return album;
private void initData() {
artists = new HashMap();
InputStream is = this.getClass().getClassLoader().getResourceAsStream("org/richfaces/demo/tree/data.txt");
ByteArrayOutputStream os = new ByteArrayOutputStream();
byte[] rb = new byte[1024];
int read;
HttpServletRequest request = (HttpServletRequest)FacesContext.getCurrentInstance().getExternalContext().getRequest();
// System.out.println("request.getParameter(param) "+request.getParameter("param"));
//System.out.println("request.getParameter(client) "+request.getParameter("client"));
//System.out.println("request.getParameter() "+request.getParameter("c"));
try {
do {
read = is.read(rb);
if (read>0) {
os.write(rb, 0, read);
} while (read>0);
String buf = os.toString();
StringTokenizer toc1 = new StringTokenizer(buf,"\n");
String str1 = request.getParameter("albumIds");
int clientId1 =Integer.parseInt( request.getParameter("client"));
while (toc1.hasMoreTokens()) {
String str = toc1.nextToken();
StringTokenizer toc2 = new StringTokenizer(str, "\t");
String artistName = toc2.nextToken();
String albumTitle = toc2.nextToken();
String songTitle = toc2.nextToken();
toc2.nextToken();
toc2.nextToken();
String albumYear = toc2.nextToken();
Artist artist = getArtistByName(artistName,this);
Album album = getAlbumByTitle(albumTitle, artist);
String portfolios[] = new String[100];
Integer portfoliosId[] = new Integer[100];
int i = 0;
StringTokenizer st = new StringTokenizer(str1, ",");
while (st.hasMoreTokens()) {
portfolios[i] = st.nextToken();
if((songTitle.equals(portfolios))&&(!(songTitle == ""))){
//System.out.println("ifff");
album.setSelected(true);
i++;
album.setYear(new Integer(albumYear));
} catch (IOException e) {
throw new RuntimeException(e);
public Object getState1() {
return state1;
public void setState1(Object state1) {
this.state1 = state1;
public Object getState2() {
return state2;
public void setState2(Object state2) {
this.state2 = state2;
public void walk(TreeNode node, List<TreeNode> appendTo, Class<? extends TreeNode> type) {
if (type.isInstance(node)){
appendTo.add(node);
Iterator<Map.Entry<Object, TreeNode>> iterator = node.getChildren();
System.out.println("walk node.getChildren() "+node.getChildren());
while(iterator.hasNext()) {
walk(iterator.next().getValue(), appendTo, type);
public ArrayList getLibraryAsList(){
ArrayList appendTo = new ArrayList();
System.out.println("getLibraryAsList appendTo "+appendTo);
walk(this, appendTo, Song.class);
return appendTo;
/************************Library.java*********End****************/
/************************PostbackPhaseListener.java*********Start****************/
package org.richfaces.treemodeladaptor;
import java.util.Map;
import javax.faces.context.ExternalContext;
import javax.faces.context.FacesContext;
import javax.faces.event.PhaseEvent;
import javax.faces.event.PhaseId;
import javax.faces.event.PhaseListener;
public class PostbackPhaseListener implements PhaseListener {
public static final String POSTBACK_ATTRIBUTE_NAME = PostbackPhaseListener.class.getName();
public void afterPhase(PhaseEvent event) {
public void beforePhase(PhaseEvent event) {
FacesContext facesContext = event.getFacesContext();
Map requestMap = facesContext.getExternalContext().getRequestMap();
requestMap.put(POSTBACK_ATTRIBUTE_NAME, Boolean.TRUE);
public PhaseId getPhaseId() {
return PhaseId.APPLY_REQUEST_VALUES;
public static boolean isPostback() {
FacesContext facesContext = FacesContext.getCurrentInstance();
if (facesContext != null) {
ExternalContext externalContext = facesContext.getExternalContext();
if (externalContext != null) {
return Boolean.TRUE.equals(
externalContext.getRequestMap().get(POSTBACK_ATTRIBUTE_NAME));
return false;
/************************PostbackPhaseListener.java*********End****************/
Edited by: rajesh_forum on Sep 17, 2008 6:13 AM
Edited by: rajesh_forum on Sep 17, 2008 6:18 AMHi
Can somebody please look into this?
Thanks
Raj
Edited by: RajICWeb on Aug 9, 2009 4:38 AM -
I have a macbook pro 15 inch mid 2012 and I want to change the hard drive, what specifications do I need to search for?
Does a Seagate - 1TB Internal Serial ATA III/Serial ATA II Solid State Hybrid Drive for Laptops - Multi with the following specifications may work??
Height
4 inches
Width
2.75 inches
Weight
3.5 ounces
Color Category
Multi
Minimum System Requirements
PC: Windows XP, Vista, 7 or 8; MacBook®, MacBook Pro or Mac Mini: Intel®
processor; OS X; Linux; internal Serial ATA III or Serial ATA II support -
I have ca. 30 pdf documents I need to search for keywords; how can I do on my MAC?
I have ca. 30 pdf documents I need to search for keywords; when I open these documents in Adobe Reader on my MAC, it shows a Search tool; however, when I search for keywords I know are in the document, none are found. How can I do a keyword search?
Do you know if the text has been OCR recognised? Are the original documents "scans"?
An easy way to find out, if you can select an individual word or letter? If you are selecting a whole block of text then the document will need to be put through Optical Character Recognition (OCR) software first to enable you to keyword search. -
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
Maybe you are looking for
-
OS 7 boot CD for Mac Plus?
Hello and greetings from Switzerland. Before getting to topics let me introduce myself a bit. I'm a private collector of old NeXT, Atari and Apple hardware, living in Switzerland and as long as being no native speaker I hope You can understand my Eng
-
Create PDF from text fields in website
Hi! Is it possible to hook up text fields in a website to a PDF document? I have a website developed in Dreamweaver/asp and I would like the ability to create a PDF based on values from different text fields (10-12). Today we first insert the values
-
Next to the 'back' or 'forward' arrows there used to be a drop down box you could check that would give you a recent history of visited pages. You could click on one and return to it. Where is this option in Firefox 4?
-
If anybody can Help me! installing solaris 8 in intel chipset 820v
Hi All, During installation of Solaris 7 or 8 in Intel plateform, I have encountered following problem listed below.I have also checked the motherboard's chipset with Sun's Hardware Compatiability List, it is there. My Machine: Intel PIII Motherboard
-
Edit the description metadata field.
Is it possible to edit the 'description' field through a script. I've been trying off and on all day and coming up dry. here is what i have now thanks to some script i've found from John Beardsworth (thanks, btw!!) that i managed to narrow to my nee