DefaultMutableTreeNode inorder traversal ?
Hi,
I need to traverse a JTree using inorder traverse. any suggestion??? help pls.
Inorder Traverse is visiting all nodes of tree from left to right.
Hi.
Inorder traversal will only work with binary trees since you don't know when to process the current node when you've got variating number of children. Let's say you've got a (binary) tree like this:
1
2 3
4 5Then inorder would give you 4, 2, 5, 1, 3 - after the rule: first process the left child, then the root (the current node), then the right child.
But what would it look like in case you've got a tree like that:
1
/|\
2 3 4When would the '1' appear in the output? pre- and postorder will work fine becaue processing the curent node before or after the children is easy - but you don't know the position when to process it when using inorder traversal.
Of course you could count the children and say that the 'middle' is between them - e.g. with five children, the root is to be processed after child #2 or #3 to be in the middle - but that'd be no inorder processing since that doesn't really exist for tree with variable children amounts.
I might be the case that you know that your JTree will always have two or less children for each node - the you just have to process the current node after the first and before the second child. But when using DefaultMutableTreeNode you cannot be sure about this since that class allows any number of children.
HTH, cheers
kelysar
Similar Messages
-
Binary tree using inorder traversal algorithm
I need to draw a Binary tree using Inorder traversal algorithm.. in java applets using rectangles and ellipse objects.. can anyone help me about this ? I will be really thankful to yu
I think this is my psychic Sunday, so here's my attempt at answering
this vaguely stated question. First have a look at this fine piece of
ASCII art:-------------------------------------------- ^ ^
| A T | | |
| | | root
---------L-----------------------R---------+ | v
| B | C | |
| | | |
| | | height
| | | |
| | | |
| | | |
| | | |
| | | |
| | | |
| | | |
-------------------------------------------+ v
<--------------------width------------------->Suppose you have a rectangle 'width' wide and 'height' high. The root
of the tree can be drawn at position T and (if present), two lines can be
drawn to the positions L and R respectively. Now recursively call your
same method using the computed rectangle A and B for the left and
right subtrees L and R respectively.
kind regards,
Jos -
Inorder traversal manipulating array
I have an array of integers in main that I store into a binary search tree, I want to use my inorder traversal routine to store the values back into the array contained in main.
Shouldn't I be able to refrence the array in main if I declare it as protected?
I get an unresolved symbol error in NetBeans when I try this. What is the proper way.
again Thanks for any help given.I have an array of integers in main that I store into
a binary search tree, I want to use my inorder
traversal routine to store the values back into the
array contained in main.Just out of curiosity -- if you store these values back in the array again the way you intend to, you've
effectively sorted the original array. Why not sort the array in the first place? You don't need that
search tree at all ...
kind regards,
Jos -
Binary tree inorder traversal without recursion
Using Java, write a method that does an in-order traversal of a binary tree WITHOUT using recursion. based on the following code
BTreeNode.java
public class BTreeNode
public BTreeNode LEFT;
public BTreeNode RIGHT;
public String VALUE;
BTreeUtil.java
public class BTreeUtil
public static void listNodes(BTreeNode a_oRootNode)
// insert code here...
}This is definitely the wrong place to post this. Nevertheless you'll have to use a stack. While traversing down the tree you push the parents onto the stack.
stephan -
N-ary Trees non-recursive traversal algorithms
Hi,
Non-recursive traversals are needed when you are unsure how big the tree's will be. So far all the algorithms I have seen either use their own internal stack
or threading to climb back up the tree.
Here's my attempt that seems to work but I would value so critical evaluation
* An extension of the CommonAST that records the line and column
* number. The idea was taken from <a target="_top"
* href="http://www.jguru.com/jguru/faq/view.jsp?EID=62654">Java Guru
* FAQ: How can I include line numbers in automatically generated
* ASTs?</a>.
* @author Oliver Burn
* @author lkuehne
* @version 1.0
* @see <a target="_top" href="http://www.antlr.org/">ANTLR Website</a>
public class DetailAST
public AST getFirstChild()
public AST getNextSibling()
public int getChildCount()
public DetailAST getParent()
public int getChildCount(int aType)
public String getText()
}This was cut back just to give you enough info
public static AST getLeftMostChild(DetailAST ast) {
DetailAST tempAst = ast.getFirstChild();
while (tempAst.getFirstChild() != null) {
tempAst = tempAst.getFirstChild();
return tempAst;
public static void traverseASTInOrder(DetailAST root) {
DetailAST current = getLeftMostChild(ast);
processNode(current);
while (current != root) {
if (current == current.getParent().getFirstChild()) {
processNode(current.getParent());
if (current.getNextSibling() != null) {
DetailAST sibling = current.getNextSibling();
if (sibling.getChildCount() != 0) {
current = (DetailAST) getLeftMostChild(sibling);
processNode(current);
} else {
current = sibling;
processNode(current);
} else {
current = current.getParent();
// do stuff at inorder traversal
public static void processNode(AST current) {
System.out.println(current.getText());
}for pre-order and post-order John Cowan put forward this algorithm
http://lists.xml.org/archives/xml-dev/199811/msg00050.html
traverse(Node node) {
Node currentNode = node;
while (currentNode != null) {
visit(currentNode); //pre order
// Move down to first child
Node nextNode = currentNode.getFirstChild();
if (nextNode != null) {
currentNode = nextNode;
continue;
// No child nodes, so walk tree
while (currentNode != null) {
revisit(currentNode) // post order
// Move to sibling if possible.
nextNode = currentNode.getNextSibling();
if (nextNode != null) {
currentNode = nextNode;
break;
// Move up
if (currentNode = node)
currentNode = null;
else
currentNode = currentNode.getParentNode();
}Any comments, criticisms or suggestions ?
regards
David ScurrahStack is recursion? As far as I know recursion is when
function (method) calls itself. Just using some
Collection, which java.util.Stack implements is not
recursion.
Regards
PawelStacks are used to implement recursive algorithms. What happens in most languages when you make a function call? Each function has an "activation record" where it stores its local variables and parameters. This activation record is usually allocated on a stack. Thus for any recursive algorithm, there is a non-recursive algorithm that uses a stack.
In the OP's case you don't need a stack because of the peculiarities of tree traversal when you have a pointer to the parent node. (Namely, no cycles and you can get back to where you've been) So the algorithms he gave should work fine.
My only "criticism" would be that it may be more useful to implement these algorithms with the iterator pattern. So you would have a tree with some functions like:
public class Tree{
public TreeIterator inOrderIteraror();
public TreeIterator preOrderIterator();
}Where the TreeIterator would look like a java.util.Iterator, except maybe you want some additional utility methods in there or something.
Other than that, non-recursive algorithms are defnitely the way to go. -
Breadth First Traversal of a Tree...
Hi,
I want to make a program to print every node of a tree in a Breadth First Search (BFS)/Traversal. Since, BFS searches a tree in levels (i.e. 1st the root, then it's Children, then Grand Children etc from left to right), this is where I'm stuck. Here is my TreeNode class:
class TreeNode {
Object element;
TreeNode left;
TreeNode right;
public TreeNode(Object o) {
element = o;
}Each node has a reference to its Children nodes etc. Here is how my tree looks like. Mine is similar to this: http://www.codeproject.com/KB/vb/SimpleBTree.aspx
All the lectures I have read in the net are talking about Queue, but my problem is reading the tree in BFS Traversal order. It's almost 4 days I'm trying to solve this probelm, but can't come up with something. Any help is greatly appreciated.
Here is my Binary Tree class:
public class BinaryTree {
private TreeNode root;
private int size = 0;
/** Create a default binary tree */
public BinaryTree() {
/** Create a binary tree from an array of objects */
public BinaryTree(Object[] objects) {
for (int i = 0; i < objects.length; i++)
insert(objects);
/** Insert element o into the binary tree
* Return true if the element is inserted successfully */
public boolean insert(Object o) {
if (root == null)
root = new TreeNode(o); // Create a new root
else {
// Locate the parent node
TreeNode parent = null;
TreeNode current = root;
while (current != null)
if (((Comparable)o).compareTo(current.element) < 0) {
parent = current;
current = current.left;
else if (((Comparable)o).compareTo(current.element) > 0) {
parent = current;
current = current.right;
else
return false; // Duplicate node not inserted
// Create the new node and attach it to the parent node
if (((Comparable)o).compareTo(parent.element) < 0)
parent.left = new TreeNode(o);
else
parent.right = new TreeNode(o);
size++;
return true; // Element inserted
/** Inorder traversal */
public void inorder() {
inorder(root);
/** Inorder traversal from a subtree */
private void inorder(TreeNode root) {
if (root == null) return;
inorder(root.left);
System.out.print(root.element + " ");
inorder(root.right);
/** Postorder traversal */
public void postorder() {
postorder(root);
/** Postorder traversal from a subtree */
private void postorder(TreeNode root) {
if (root == null) return;
postorder(root.left);
postorder(root.right);
System.out.print(root.element + " ");
/** Preorder traversal */
public void preorder() {
preorder(root);
/** Preorder traversal from a subtree */
private void preorder(TreeNode root) {
if (root == null) return;
System.out.print(root.element + " ");
preorder(root.left);
preorder(root.right);
/** Inner class tree node */
private static class TreeNode {
Object element;
TreeNode left;
TreeNode right;
public TreeNode(Object o) {
element = o;
/** Get the number of nodes in the tree */
public int getSize() {
return size;
/** Search element o in this binary tree */
public boolean search(Object o){
TreeNode temp = root;
boolean found = false;
if(temp == null)
found = false;
else if(((Comparable)(temp.element)).compareTo(o) == 0 && temp != null)
found = true;
else if(((Comparable)temp.element).compareTo(o) > 0){
root = temp.left;
found = search(o);
else{
root = temp.right;
found = search(o);
return found;
/** Display the nodes in breadth-first traversal */
public void breadthFirstTraversal(){
TreeNode temp = root;
// TreeNode leftChild = temp.left;
// TreeNode rightChild = temp.right;
MyQueue s = new MyQueue();
s.enqueue(root);
// while (s.getSize() == 0){
System.out.println(s);
// private void breadthFirstTraversal(TreeNode node){ChangBroot wrote:
All the lectures I have read in the net are talking about Queue, but my problem is reading the tree in BFS Traversal order. It's almost 4 days I'm trying to solve this probelm, but can't come up with something. Any help is greatly appreciated. One simple strategy is to make an ordinary recursive traversal of the tree. Along in the traversal you keep an array of linked lists. When you visit a node you just add it to the list at the entry in the array corresponding to the depth of this node.
After the traversal you have an array with linked lists. Each list holds the nodes found at a certain tree depth. So each list holds all nodes corresponding to a specific tree "breadth", namely all nodes found at the same tree depth. -
HELP: In-Order traversal of a BinaryTree in Java
Hey,
We were instructed to build a Node class and a BinaryTree class in java and do an in-order traverse on it. (Print out in order) I know that I am building my tree correctly (w/ pointers, etc.) because I can use System.out.println() to tell me. However, we were instructed to pass one string around and have all the nodes add their "info" to it, in this case a String that is a persons name. So I wrote this:
In my BinaryTree class where root is a Node:
public String toString()
String temp = "";
if(root != null)
temp = root.inOrder(temp);
else
temp = "";
return temp;
}And my inOrder() method looks like this in my Node class:
public String inOrder(String s)
if(left != null)
left.inOrder(s);
s = s + "\n" + info;
if(right != null)
right.inOrder(s);
return s;
}However, Im not sure as to why its only printing out the root's info? And not the rest!! BTW, he told me that is the correct algorithm for the inOrder traverse, I just wasnt passing the String parameter right...
FROM THE TEACHER:
"The way you are traversing the tree is fine. By that I mean you are moving from node to node through the tree correctly. Your problem comes from the way you are passing parameters. What you are trying to accomplish here is to create a String called "temp" in your Binary Tree class and then, as you "visit" each node, that node should append its "info" to the string. When you have visited all the nodes, the string is returned to the Binary tree object with all the info concatenated into that one string.
That means that that one string must be passed to each node and returned from each node. Notice that in your code for the "inOrder" method, you create a new empty string in that node, add the info for that node and then return it. It doesn't get passed on to the next node."
Any help??? Thanks alot! :)BC2210 wrote:
Im confused though because isnt that what Im doing in the toString() method of the BinaryTree class? temp = root.inOrder()? And then return temp from that?Yes, but root.inOrder() only returns the info from the root, since the inOrder method doesn't do anything with the data returned from subsequent inOrder() calls.
public String inOrder(String s)
if(left != null)
left.inOrder(s); // calls inOrder() on the left node, but doesn't do anything with the return value, so it's like this was never called at all
s = s + "\n" + info;
if(right != null)
right.inOrder(s); // same here
return s;
} -
Combining recursive tree traversal subroutine and calling method?
I wrote the following bit to take a TreeMap of string (words) and build into one long inorder traversed string (alphabetical order). Works fine-this isn't a do my homework problem =).
But I have two questions:
1. How, if any, is it possible to combine the recursive function and the one that calls it into one consolidated subroutine.
2. A little off topic, but can objects of different primitive types (like an int 2D array and a string) be stored with in each node? How can I specify which one is the "key" on traversal (the word), how can i access the other data (array)?
I'm bout to go over some documentation myself, I know I'll find something, but just wanted to know the general consensus on this type of execution. Thanks.
public String toString() {
inOrderTreeResult = "Result of this tree is: ";
inOrderTreeResult += (buildString(root));
return inOrderTreeResult;
public String buildString(TreeNode node){
if (node != null) {
buildString( node.left );
inOrderTreeResult += (node.item + "\n");
buildString( node.right );
return inOrderTreeResult;
}I'm not so sure I understand. Lemme show some code and explain. I have a simple treemap implementation to create an alphabetical index of words that appear in a text file. Currently the one data in each node is the String word. I want to be able to include the line number and number of iterations on each line that it appears. I could do it sloppily by putting all that information into one string and parsing it out later, or I thought maybe I could somehow add a 2D array (actually a vector for expandability) that I can access later when i print out the index.
Here's the constructor class of the Tree:
static class TreeNode {
String item;
TreeNode left;
TreeNode right;
TreeNode(String str) {
item = str;
} On insertion, it traverses for the proper position on the tree and should add the string, if it exists, I should be able to access the vector and increment counters, add more line numbers, whatever.
Thanks. -
Where did My B_Tree in-order-trave go wrong ?
Hi
Could someone check my code please
I am trying to in-order trave a Binary tree
The left hand side seams Ok .
But when I reach the root and then move to the right .... ?
Is there is another way to re write my code . It seams to be too long
Thanks
import java .io .* ;
public class BTreeA {
// instance variabels FOR A STUDENT
public String StId;
public String StName;
public int countL = 0 ;
public int countR =0 ;
// intialise the left and right children to null
private BTreeA left = null;
private BTreeA right = null;
static BTreeA root = null; // Used to keep track of top of tree
static BTreeA temp = null; // temprary binary tree intialised to null
static BTreeA ptemp = null; // the parentof the cheldrin intialised to null
static BTreeA ctemp = null; // the parentof the cheldrin intialised to null
static BTreeA c2temp = null; // the parentof the cheldrin intialised to null
// This method is used to add a new node into the tree.
//////ccccccccccccccccccccccccccccccccccc////////////////
//////ccccccccccccccccccccccccccccccccccc////////////////
//////ccccccccccccccccccccccccccccccccccc////////////////
// the constructor method
public BTreeA(String id, String name) {
// App-spec part
this.StId = new String(id);
this.StName = new String(name);
// Data structure part
this.left = null;
this.right = null;
// Find out where new node is to go and insert it
if(root == null) { // There's no tree yet
root = this; // the first node is located in the root
System.out .println (" this is the first node inserted in the root " );
}else { // there is a tree and the root is occupied
temp = root; // when the root is occupied
// make the temp equal the root
// loop
while (temp != null) { // descend tree to find parent for
// the new node (( we know that temp != null becausewe made it
// equals to the root
ptemp = temp; // make the temporary parent equal to the temp
// ie equal to the root as well for the start of the loop
// and each time the loop restarts ptemp = new position of temp
if(this.StId.compareTo(temp.StId)< 0){
temp = temp.left; // move to the left
countL ++ ;
// System.out .println ("Moving to the left, and this is the move No. : " + countL );
// temp = null ; // to getout of the loop
}else{
temp = temp.right;
countR++;
// System.out .println ("Moving to the right, and this is the move No. : " + countR);
// temp = null ; // to getout of the loop
}// end if
}// end of loop
// here we insert the node into the tree
if(this.StId.compareTo(ptemp.StId) < 0 ){
ptemp.left = this;
// countL++;
// System.out .println ("The new node will be inserted the left for move No. : " + countL );
}else{
//if(this.StId.compareTo(ptemp.StId) < 0 ){
ptemp.right = this;
//countR++;
// System.out .println ("The new node will be inserted the right for move No. : "+ countR );
}// end of nested if
}// end of method
// Useful method for debugging
// print out all nodes in the tree
// in sorted order, "inorder traversal"
// Hint: Should take about 10 or 20 lines of code
// ... if you think you need more then your logic
// is probably more complicated than it needs to be.
//////s/s/s/s/s/s/s/s/s/s/s/s/s/s/s/s/s/s/////
//b/b/b/b/b/b/b/bb/b/b/b/b/b/b/b/b/b/b'/b
public void InOrderTraverse() {
// start from the root
c2temp = root ;
temp = root ;
while (temp != null ){
ptemp = temp ;
// if( ptemp != null ) {
while (ptemp != null ){
temp = ptemp ;
ptemp = ptemp.left ;
// then print the information of that child
System.out.println("\n"+temp.StId); // Write out the ID field
System.out.println(temp.StName ); // Student name
System.out.println( "***OOOOO***oooo***OOOO***");
// here we find the parent for the child
while(temp != null ){
ctemp = temp; // the value of the child
temp = c2temp ; // ie = root
// in here we look for a node before the last one
while (temp.StId .compareTo (ctemp.StId )>0){
ptemp = temp ;
temp = temp.left ;
//// KKKKKKKKKKKKKKKKKKKKKKKK ;;;;;
/// from here we check if we can start to go right ////
if ( ptemp.right != null
&& ptemp.StId .compareTo (ptemp.right.StId )<=0){
System.out.println("\n"+ptemp.StId); // Write out the ID field
System.out.println(ptemp.StName ); // Student name
System.out.println( "***OOOOO***oooo***OOOO***");
ptemp = ptemp.right ;
c2temp = ptemp ;
temp = ptemp ;
// go to the last child in the left
while (ptemp != null && ptemp.left != null ){
temp = ptemp ;
ptemp = ptemp.left ;
System.out.println("\n"+ temp.StId); // Write out the ID field
System.out.println( temp.StName ); // Student name
System.out.println( "***OOOOO***oooo***OOOO***");
ptemp = temp ;
}else {
temp = ptemp ;
System.out.println("\n"+temp.StId); // Write out the ID field
System.out.println(temp.StName ); // Student name
System.out.println( "***OOOOO***oooo***OOOO***");
} // end of if
}// end of here we find the parent for the child
} // end first loop
} // end of void trversal method
///// MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM ////////////////
///// MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM ////////////////
///// MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM ////////////////
///// MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM ////////////////
// // in here we search for a student
public void Search(String id) {
int val;
temp = root;
while (temp != null) { // descend tree to find parent for
if((val = id.compareTo(temp.StId)) == 0) {
System.out.println("\n"+"Student ID "+id+" is in the tree!");
System.out.println("\n"+"Student name is : "+temp.StName);
temp = null; // to get out of loop
else if (val < 0)
temp = temp.left;
else temp = temp.right; // else it must be greater
///pppppppppppppppppppp rrrrrrrrr iiiiiiiiiii nnnnnnnnn ttttttttt //
public void printAll (){
// start from the root
temp = root ;
// loop and check for null
while ( temp != null ){
// if both left and right children do not exist
if( temp.left == null && temp.right == null ){
// then print the information of that parent
System.out.println("\n"+temp.StId); // Write out the ID field
System.out.println(temp.StName ); // Student name
System.out.println("\n"+"************");
// move to the left
temp = temp.left ;
}else { // if any of the children exist then
// check the left
if (temp.right != null ){
temp =temp.right ;
}else{
if(temp.left != null ){
temp = temp.left ;
}// end of if
}// end of if
}// end of if
} // end of loop
} // end of void method
// protected void intrav(pTwoChildNode p){
// if(p == null)
// return;
// intrav(p.getLeft());
// System.out.print(p.getData()+" ");
// intrav(p.getRight());
///////////ooooooooooooooooooooooooooooo///////////////
///go throu the tree and sorted out
public void sortBTree (){
BTreeA standBy = root ;
while (standBy != null && standBy.left != null && standBy.right != null ){
// compare
if(standBy .left .StId.compareTo (standBy .StId) < 0 ){
temp = standBy ;
temp .StId = standBy .left.StId ;
temp.StName = standBy.left .StName ;
standBy .left.StId = standBy.StId ;
standBy.left.StName = standBy.StName ;
standBy .left .StId = temp.StId ;
standBy .left .StName = temp.StName ;
System.out.println("\n"+temp.StId); // Write out the ID field
System.out.println(temp.StName ); // Student name
System.out.println("\n"+"************");
System.out.println("\n"+standBy.StId); // Write out the ID field
System.out.println(standBy.StName ); // Student name
System.out.println("\n"+"************");
// standBy = standBy.right ;
//move to the left
// standBy = standBy.left ;
}else{
if(standBy .left .StId.compareTo (standBy .StId) > 0 ){
standBy = standBy.right ;
///////////ooooooooooooooooooooooooooooo///////////////
///////////ooooooooooooooooooooooooooooo///////////////
public static void main(String Args[]){
new BTreeA("7", "Fergal");
// root.InOrderTraverse();
new BTreeA("9", "Frank");
//root.InOrderTraverse();
new BTreeA("6", "Fiona");
// root.InOrderTraverse();
new BTreeA("8", "John");
//root.InOrderTraverse();
new BTreeA("3", "Elizabeth");
// root.InOrderTraverse();
new BTreeA( "2", "Nuara");
// root.InOrderTraverse();
new BTreeA("1", "Aziza");
// root.InOrderTraverse();
new BTreeA("10", "Radwan");
root.InOrderTraverse();
new BTreeA("0", "Sommer");
root.InOrderTraverse();
new BTreeA( "-1", "Tibrah");
root.InOrderTraverse();
root.Search ("1");
root.Search ("123");
// root.sortBTree ();
// print all the contents of the tree
// root.printAll ();
// GIVE YOURSELF TIME TO READ THE SCREAN
System.out.println ("\n"+"\n" +"Please Press ENTER to terminate the application ." ) ;
try {
System.in.read ();
}catch (IOException e ){
}Please use the formatting tags.
import java .io .* ;
public class BTreeA {
// instance variabels FOR A STUDENT
public String StId;
public String StName;
public int countL = 0 ;
public int countR =0 ;
// intialise the left and right children to null
private BTreeA left = null;
private BTreeA right = null;
static BTreeA root = null; // Used to keep track
ack of top of tree
static BTreeA temp = null; // temprary binary tree
ree intialised to null
static BTreeA ptemp = null; // the parentof the
the cheldrin intialised to null
static BTreeA ctemp = null; // the parentof the
the cheldrin intialised to null
static BTreeA c2temp = null; // the parentof the
the cheldrin intialised to null
// This method is used to add a new node into the
tree.
//////ccccccccccccccccccccccccccccccccccc//////////////
//////ccccccccccccccccccccccccccccccccccc//////////////
//////ccccccccccccccccccccccccccccccccccc//////////////
// the constructor method
public BTreeA(String id, String name) {
// App-spec part
this.StId = new String(id);
this.StName = new String(name);
// Data structure part
this.left = null;
this.right = null;
// Find out where new node is to go and insert it
if(root == null) { // There's no tree yet
root = this; // the first node is located in the
System.out .println (" this is the first node inserted in the root " );
}else { // there is a tree and the root is occupied
temp = root; // when the root is occupied
// make the temp equal the root
// loop
while (temp != null) { // descend tree to find
find parent for
// the new node (( we know that temp != null
l becausewe made it
// equals to the root
ptemp = temp; // make the temporary parent equal
ual to the temp
// ie equal to the root as well for the start of
f the loop
// and each time the loop restarts ptemp = new
w position of temp
if(this.StId.compareTo(temp.StId)< 0){
temp = temp.left; // move to the left
countL ++ ;
// System.out .println ("Moving to the left, and this is the move No. : " + countL );
// temp = null ; // to getout of the loop
}else{
temp = temp.right;
countR++;
// System.out .println ("Moving to the right, and this is the move No. : " + countR);
// temp = null ; // to getout of the loop
}// end if
}// end of loop
// here we insert the node into the tree
if(this.StId.compareTo(ptemp.StId) < 0 ){
ptemp.left = this;
// countL++;
// System.out .println ("The new node will be inserted the left for move No. : " + countL );
}else{
//if(this.StId.compareTo(ptemp.StId) < 0 ){
ptemp.right = this;
//countR++;
// System.out .println ("The new node will be inserted the right for move No. : "+ countR );
}// end of nested if
}// end of method
// Useful method for debugging
// print out all nodes in the tree
// in sorted order, "inorder traversal"
// Hint: Should take about 10 or 20 lines of code
// ... if you think you need more then your logic
// is probably more complicated than it needs to be.
//////s/s/s/s/s/s/s/s/s/s/s/s/s/s/s/s/s/s/////
//b/b/b/b/b/b/b/bb/b/b/b/b/b/b/b/b/b/b'/b
public void InOrderTraverse() {
// start from the root
c2temp = root ;
temp = root ;
while (temp != null ){
ptemp = temp ;
// if( ptemp != null ) {
while (ptemp != null ){
temp = ptemp ;
ptemp = ptemp.left ;
// then print the information of that child
System.out.println("\n"+temp.StId); // Write out
e out the ID field
System.out.println(temp.StName ); // Student
udent name
System.out.println(
println( "***OOOOO***oooo***OOOO***");
// here we find the parent for the child
while(temp != null ){
ctemp = temp; // the value of the child
temp = c2temp ; // ie = root
// in here we look for a node before the last one
ne
while (temp.StId .compareTo (ctemp.StId )>0){
ptemp = temp ;
temp = temp.left ;
//// KKKKKKKKKKKKKKKKKKKKKKKK ;;;;;
/// from here we check if we can start to go right
if ( ptemp.right != null
&& ptemp.StId .compareTo (ptemp.right.StId
StId )<=0){
System.out.println("\n"+ptemp.StId); // Write out
ut the ID field
System.out.println(ptemp.StName ); // Student
udent name
System.out.println(
println( "***OOOOO***oooo***OOOO***");
ptemp = ptemp.right ;
c2temp = ptemp ;
temp = ptemp ;
// go to the last child in the left
while (ptemp != null && ptemp.left != null ){
temp = ptemp ;
ptemp = ptemp.left ;
System.out.println("\n"+ temp.StId); // Write out
ut the ID field
System.out.println( temp.StName ); // Student
udent name
System.out.println(
println( "***OOOOO***oooo***OOOO***");
ptemp = temp ;
}else {
temp = ptemp ;
System.out.println("\n"+temp.StId); // Write out
ut the ID field
System.out.println(temp.StName ); // Student
udent name
System.out.println(
println( "***OOOOO***oooo***OOOO***");
} // end of if
}// end of here we find the parent for the child
} // end first loop
} // end of void trversal method
///// MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM
///// MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM
///// MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM
///// MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM
// // in here we search for a student
public void Search(String id) {
int val;
temp = root;
while (temp != null) { // descend tree to find parent
for
if((val = id.compareTo(temp.StId)) == 0) {
System.out.println("\n"+"Student ID "+id+" is in the tree!");
System.out.println("\n"+"Student name is : "+temp.StName);
temp = null; // to get out of loop
else if (val < 0)
temp = temp.left;
else temp = temp.right; // else it must be
t be greater
///pppppppppppppppppppp rrrrrrrrr iiiiiiiiiii nnnnnnnnn ttttttttt //
public void printAll (){
// start from the root
temp = root ;
// loop and check for null
while ( temp != null ){
// if both left and right children do not exist
if( temp.left == null && temp.right == null ){
// then print the information of that parent
System.out.println("\n"+temp.StId); // Write out
out the ID field
System.out.println(temp.StName ); // Student
dent name
System.out.println("\n"+"************");
// move to the left
temp = temp.left ;
}else { // if any of the children exist then
// check the left
if (temp.right != null ){
temp =temp.right ;
}else{
if(temp.left != null ){
temp = temp.left ;
}// end of if
}// end of if
}// end of if
} // end of loop
} // end of void method
// protected void intrav(pTwoChildNode p){
// if(p == null)
// return;
// intrav(p.getLeft());
// System.out.print(p.getData()+" ");
// intrav(p.getRight());
///////////ooooooooooooooooooooooooooooo///////////////
///go throu the tree and sorted out
public void sortBTree (){
BTreeA standBy = root ;
while (standBy != null && standBy.left != null &&
& standBy.right != null ){
// compare
if(standBy .left .StId.compareTo (standBy .StId) <
< 0 ){
temp = standBy ;
temp .StId = standBy .left.StId ;
temp.StName = standBy.left .StName ;
standBy .left.StId = standBy.StId ;
standBy.left.StName = standBy.StName ;
standBy .left .StId = temp.StId ;
standBy .left .StName = temp.StName ;
System.out.println("\n"+temp.StId); // Write out the ID field
System.out.println(temp.StName ); // Student name
System.out.println("\n"+"************");
System.out.println("\n"+standBy.StId); // Write out the ID field
System.out.println(standBy.StName ); // Student name
System.out.println("\n"+"************");
// standBy = standBy.right ;
//move to the left
// standBy = standBy.left ;
}else{
if(standBy .left .StId.compareTo (standBy .StId) > 0 ){
standBy = standBy.right ;
///////////ooooooooooooooooooooooooooooo///////////////
///////////ooooooooooooooooooooooooooooo///////////////
public static void main(String Args[]){
new BTreeA("7", "Fergal");
// root.InOrderTraverse();
new BTreeA("9", "Frank");
//root.InOrderTraverse();
new BTreeA("6", "Fiona");
// root.InOrderTraverse();
new BTreeA("8", "John");
//root.InOrderTraverse();
new BTreeA("3", "Elizabeth");
// root.InOrderTraverse();
new BTreeA( "2", "Nuara");
// root.InOrderTraverse();
new BTreeA("1", "Aziza");
// root.InOrderTraverse();
new BTreeA("10", "Radwan");
root.InOrderTraverse();
new BTreeA("0", "Sommer");
root.InOrderTraverse();
new BTreeA( "-1", "Tibrah");
root.InOrderTraverse();
root.Search ("1");
root.Search ("123");
// root.sortBTree ();
// print all the contents of the tree
// root.printAll ();
// GIVE YOURSELF TIME TO READ THE SCREAN
System.out.println ("\n"+"\n" +"Please Press ENTER to terminate the application ." ) ;
try {
System.in.read ();
}catch (IOException e ){ -
Hi,everyone,I am just new to java.And now I got a problem with storing the following expression into a binary tree:
The expression is like: ((a/b)+((c-d)*e)) in a txt file.
so,what i want to do is to store variable and operation(+-*/)into a tree.And calculate that by using preorder traversal such as
+(/(a,b),*(-(c,d),e)).However,i even don't know how to start coding.
+
a b - e
c d
the data i want to be stored in a tree will be like above.Then,I need to use inorder traversal to display the final formula like ((a/b)+((c-d)*e))
Please get me some help.Thank you very much from everybody!Hi,
don't have any code to answer your question but here's what I'll suggest:
1) Define a class whose job will be to represent a simple expression. A simple expression is defined by '<exprX> <operator> <exprY>'. In this class, you must include a way to distinguish expressions from variables.
With your sample, there would be N expressions:
expr1 = (a / b)
expr2 = (c - d)
expr3 = (expr2 * e)
expr4 = (expr1 + expr3)
2) Define a class whose job will be to parse the formula, and create the expressions. The idea would be to find operators, and create expressions on left / right sides of the operators (I agree, it's a little harder than that, but I only have ideas right now...)
Also you'll have to store some kind of 'level info', perhaps here should be the use of the tree, keeping track of each level of computation (expr4 will be at top level, then expr3 under it, then expr2 and expr1)
Use of recursion seems evident here (and seems simple to apply to a tree structure):
- first parse will give expr4 = (expr1 + expr3) (both have to be parsed again)
- second parse will occur on expr1 = (a / b) and expr3 = (expr2 * e) (then expr3 has to be parsed)
- third parse will occur on expr2 = (c - d)
That's my two cents... sorry missing time for more help, try starting with this I'll follow the thread and help more if I can!
Regards. -
Hello,
The problem I'm having is how to empty a binary tree. Here is my code for MyBinaryTree:
public class MyBinaryTree implements BinaryTree {
private BinaryTreeNode root;
protected static int numNodes;
private static String tree = "";
* Constructor that creates a binary tree with a root.
* @param r The root node
* @param num The number of nodes
public MyBinaryTree(BinaryTreeNode r, int num) {
root = r;
numNodes = num;
* Method to make the binary tree empty.
public void makeEmpty() {
root.left = null;
root.right = null;
root = new BinaryTreeNode(null,null,null,null,null);
numNodes = 0;
* Method to make a root with key k and element el.
* @param k The key of the root
* @param el The element in the root
public void makeRoot(Comparable k, Object el) {
root = new BinaryTreeNode(k,el);
numNodes++;
* Method to return the root of the binary tree.
* @return The root of the tree
public BinaryTreeNode root() {
return root;
* Method to return the left child of a node.
* @param node The node whose left child is wanted.
* @return The left child of the node
* @see NoNodeException
public BinaryTreeNode leftChild(BinaryTreeNode node) throws NoNodeException {
if (node.left == null) throw new NoNodeException("No left child!");
else return node.leftChild();
* Method to set the left child of node "node".
* @param node The node to be given a left child
* @param child The node to be set as left child
public void setLeftChild(BinaryTreeNode node, BinaryTreeNode child) {
node.setLeftChild(child);
numNodes++;
* Method to return the right child of a node.
* @param node The node whose right child is wanted.
* @return The right child of the node
* @see NoNodeException
public BinaryTreeNode rightChild(BinaryTreeNode node) throws NoNodeException{
if (node.right == null) throw new NoNodeException("No right child!");
else return node.rightChild();
* Method to set the right child of node "node".
* @param node The node to be given a right child
* @param child The node to be set as right child
public void setRightChild(BinaryTreeNode node, BinaryTreeNode child) {
node.setRightChild(child);
numNodes++;
* Method to return the parent of a node.
* @param node The node whose parent is wanted.
* @return The parent of the node
* @see NoNodeException
public BinaryTreeNode parent(BinaryTreeNode node) throws NoNodeException {
if (node.p == null) throw new NoNodeException("No parent!");
else return node.parent();
* Method to set the parent of node "node".
* @param node The node to be given a parent
* @param pt The node to be set as parent
public void setparent(BinaryTreeNode node, BinaryTreeNode pt) {
node.setParent(pt);
numNodes++;
* Method to return the key of the specified node.
* @param node The node with the key to be returned
* @return The key of the node
public Comparable getKey(BinaryTreeNode node) {
return node.getKey();
* Method to set the key of the specified node.
* @param node The node for which the key will be set.
* @param k The key to be set.
public void setKey(BinaryTreeNode node, Comparable k) {
node.setKey(k);
* Method to get the element in the specified node.
* @param node The node with the element to be returned.
* @return The element in the node.
public Object getElement(BinaryTreeNode node) {
return node.getElement();
* Method to put an element into the specified node.
* @param node The node that will have an element put in it.
* @param o The element to be inserted.
public void setElement(BinaryTreeNode node, Object o) {
node.setElement(o);
* Method to add a left child to the specified node.
* @param theNode The node that the left child will be added to.
* @param k The key associated with the left child.
* @param el The element in the left child.
public void addLeftChild (BinaryTreeNode theNode, Comparable k, Object el) {
BinaryTreeNode temp = new BinaryTreeNode(k,el);
temp.setParent(theNode);
theNode.setLeftChild(temp);
numNodes++;
* Method to add a right child to the specified node.
* @param theNode The node that the right child will be added to.
* @param k The key associated with the right child.
* @param el The element in the right child.
public void addRightChild (BinaryTreeNode theNode, Comparable k, Object el) {
BinaryTreeNode temp = new BinaryTreeNode(k,el);
temp.setParent(theNode);
theNode.setRightChild(temp);
numNodes++;
* Method to remove the left child of the specified node.
* @param theNode The node which the left child will be removed.
public void removeLeftChild(BinaryTreeNode theNode) {
((BinaryTreeNode)(theNode.left)).p = null;
theNode.left = null;
numNodes--;
* Method to remove the right child of the specified node.
* @param theNode The node which the right child will be removed.
public void removeRightChild(BinaryTreeNode theNode) {
((BinaryTreeNode)(theNode.right)).p = null;
theNode.right = null;
numNodes--;
* Private method to perform an inorder traversal on the tree.
* @param t A MyBinaryTree object
* @param n The starting node.
private static String inorderPrint(MyBinaryTree t, BinaryTreeNode n) {
String spaces = "";
for (int i = 0; i < (numNodes - 1)/2; i++) spaces += " ";
if (n.left != null || n.right != null) inorderPrint(t,t.leftChild(n));
tree += spaces + n.getElement();
if (n.left != null || n.right != null) inorderPrint(t,t.rightChild(n));
return tree;
* Private method to perform an inorder traversal on the tree.
* @param t A MyBinaryTree object
* @param n The starting node.
* @param pos The current position in the tree.
* @return A tree with an asterix beside the current position
private static String inorderPrint2(MyBinaryTree t, BinaryTreeNode n,
BinaryTreeNode pos) {
String spaces = "";
for (int i = 0; i < (numNodes - 1)/2; i++) spaces += " ";
if (n.left != null || n.right != null) inorderPrint2(t,t.leftChild(n),pos);
if (n.getElement() == pos.getElement()) tree += spaces + n.getElement() + "*";
else tree += spaces + n.getElement();
if (n.left != null || n.right != null) inorderPrint2(t,t.rightChild(n),pos);
return tree;
* Method to return a String representation of the binary tree.
* @return String representation of the binary tree
public String toString() {
if (root.getElement() == null) return "*** Tree is empty ***";
else {
MyBinaryTree temp = new MyBinaryTree(root,numNodes);
return inorderPrint(temp,root);
* Method to return a String of the binary tree with an asterix beside the
* current position.
* @param currentPosition The current position.
* @return A String of the tree with an asterix by the current position
public String toString(BinaryTreeNode currentPosition) {
if (root.getElement() == null) return "*** Tree is empty ***";
else {
MyBinaryTree temp = new MyBinaryTree(root,numNodes);
return inorderPrint2(temp,root,currentPosition);
}Those are all the methods I'm allowed to have. When I run makeEmpty, it seems to work, but then if I do makeRoot, the old tree prints again. It's quite bizarre. Any tips on how to empty the tree correctly?Here is the BinaryTreeNode code.
public class BinaryTreeNode {
// Instance variables (Note: they are all "private")
protected Comparable key; // The key at this node
protected Object element; // The data at this node
protected BinaryTreeNode left; // Left child
protected BinaryTreeNode right; // Right child
protected BinaryTreeNode p; // The Parent
// Constructors
BinaryTreeNode( Comparable theKey, Object theElement, BinaryTreeNode lt,
BinaryTreeNode rt, BinaryTreeNode pt ) {
key = theKey;
element = theElement;
left = lt;
right = rt;
p = pt;
BinaryTreeNode( Comparable theKey, Object theElement) {
key = theKey;
element = theElement;
left = null;
right = null;
p = null;
// return the key attached to this node
public Comparable getKey() {
return key;
// set the key attached to this node to be Comparable k
public void setKey(Comparable k) {
key = k;
// return the element attached to this node
public Object getElement() {
return element;
// set the element attached to this node to be Object o
public void setElement(Object o) {
element = o;
// return left child
public BinaryTreeNode leftChild() {
return left;
// set left child to be node n
public void setLeftChild(BinaryTreeNode n) {
left = n;
// return right child
public BinaryTreeNode rightChild() {
return right;
// set right child to be node n
public void setRightChild(BinaryTreeNode n) {
right = n;
// return parent
public BinaryTreeNode parent() {
return p;
// set parent to be node n
public void setParent(BinaryTreeNode n) {
p = n;
} -
Hi,everyone,I am just new to java.And now I got a problem with storing the following expression into a binary tree:
The expression is like: ((a/b)+((c-d)*e)) in a txt file.
so,what i want to do is to store variable and operation(+-*/)into a tree.And calculate that by using preorder traversal such as
+(/(a,b),*(-(c,d),e)).However,i even don't know how to start coding.
+
a b - e
c d
the data i want to be stored in a tree will be like above.Then,I need to use inorder traversal to display the final formula like ((a/b)+((c-d)*e))
Please get me some help.Thank you very much from everybody!Right. You want to write a parser, that turns that expression into a "parse tree", which is a data structure that represents more explicitly the information expressed in the expression.
This is a homework assignment, of course.
Anyway, I'd suggest looking at StringTokenizer to first tokenize the expression into a series of (you guessed it) tokens. The parser then only deals with the series of tokens. -
Please offer help on indexing a textbook
I really need help on an assignment. It is supposed to create an index for a textbook and it has to be implemnted using trees.
Generate an index for a book.
The Input:
The input file is specified as a command-line argument (use args). Be certain to check the validity of the file.
The input file consists of a set of index entries. Each line consists of the string IX:, followed by an index entry name enclosed in braces, followed by a page number that is enclosed in braces. Each ! in an index entry name represets a sub-level. A |( represents the start of a range and a |) represents the end of the range. Occasionally, this will be the same page, and in that case, only output a single page number. Otherwise, do not collapse or expand ranges on your own. As an example, here's a sample input:
IX: Series {2}
IX: {Series!geometric|(} {4}
IX: {Euler's constant} {4}
IX: {Series!geometric|)} {4}
IX: {Series!arithmetic|(} {4}
IX: {Series!arithmetic|)} {5}
IX: {Series!harmonic|(} {5}
IX: {Euler's constant} {5}
IX: {Series!harmonic|)} {5}
IX: Series {5}
The corresponding output is:
Euler's constant: 4, 5
Series: 2-5
arithmetic: 4-5
geometric: 4
harmonic: 5
(1)You must construct a general tree with a root node(the value stored in the root node will just be the word INDEX which should be the first item printed out - this is in addition to the output specification in the text) and its children consisting of top-level index terms, the next level of children consisting of sub -level index terms and so on;
(2)Each node(except the root) must store the index term and page ranges;
(3)In the general tree implementation the siblings need to be stored in a certain way so that a certain tree traversal algorithm will print out the index in the correct way.
import java.io.*;
// BinaryTree class; stores a binary tree.
// CONSTRUCTION: with (a) no parameters or (b) an object to
// be placed in the root of a one-element tree.
// *******************PUBLIC OPERATIONS**********************
// Various tree traversals, size, height, isEmpty, makeEmpty.
// Also, the following tricky method:
// void merge( Object root, BinaryTree t1, BinaryTree t2 )
// --> Construct a new tree
// *******************ERRORS*********************************
// Error message printed for illegal merges.
* BinaryTree class that illustrates the calling of
* BinaryNode recursive routines and merge.
public class BinaryTree //extends BinaryNode
BinaryNode name = new BinaryNode();
public static void main(String []args)
String denem = "flag";
BinaryTree index = new BinaryTree(denem);
BinaryTree.insert(denem);
System.out.println(index.infix(denem));
System.exit(0);
public BinaryTree( )
name = null;
public BinaryTree( String rootItem )
BinaryNode name = new BinaryNode( rootItem, null, null );
public void printInOrder( )
//if( root != null )
name.printInOrder( );
public BinaryNode insert(String str, BinaryNode t)
if(t == null)
t = new BinaryNode(str, null, null);
else if(str.compareTo(t.root) < 0)
t.left = insert(str, t.left);
else if(str.compareTo(t.root) > 0)
t.right = insert(str, t.right);
return t;
public BinaryNode insert(String str)
BinaryNode n = root;
return insert(str, n);
// allows the pages to be printed out
public String toString()
String concat = name.getRoot();
return concat;
public static void infix(BinaryNode t)
if (t != null)
System.out.print("(");
infix(t.getLeft());
System.out.print(t);
infix(t.getRight());
System.out.print(")");
// Class binary node
final class BinaryNode
protected String root; //the name
protected BinaryNode left;
protected BinaryNode right;
//protected String pages;
public BinaryNode( )
this( null, null, null); //, null);
public BinaryNode( String root, BinaryNode left, BinaryNode right) //, String pages )
root = this.root;
left = this.left;
right = this.right;
// pages = this.pages;
* Return the size of the binary tree rooted at t.
public static int size( BinaryNode t )
if( t == null )
return 0;
else
return 1 + size( t.left ) + size( t.right );
* Return the height of the binary tree rooted at t.
public static int height( BinaryNode t )
if( t == null )
return -1;
else
return 1 + Math.max( height( t.left ), height( t.right ) );
// Print tree rooted at current node using inorder traversal.
public void printInOrder( )
if( left != null )
left.printInOrder( ); // Left
System.out.println( root ); // Node
if( right != null )
right.printInOrder( ); // Right
public String getRoot( )
return root;
public BinaryNode getLeft( )
return left;
public BinaryNode getRight( )
return right;
/*public void setElement( Object x )
element = x;
public void setLeft( BinaryNode t )
left = t;
public void setRight( BinaryNode t )
right = t;
} // end of class node
This is the solution done using linked lists and treemap.
import java.io.*; // to read the file
A red-black tree is a binary search tree where every node has two children or is a leaf.
It ensures O(log N) search times, at a cost of a more complicated insertion (and deletion)
process. In a red-black tree, every node is colored either red or black, with a black root
node, though a black root node isn't a requirement. In addition, if a node is red, its
children must be black and every path from root to leaf (or null child node) must
contain the same number of black nodes. These rules allow balancing
import java.util.TreeMap;
import java.util.Comparator;
import java.util.StringTokenizer;
public interface Iterator An iterator over a collection. Iterator takes the place of
Enumeration in the Java collections framework. Iterators differ from enumerations in two ways:
Iterators allow the caller to remove elements from the underlying collection during the iteration
with well-defined semantics.
import java.util.Iterator;
import java.util.LinkedList;
import java.util.ArrayList;
public class IndexGenerator3
private static final String START = "|(";
private static final String END = "|)";
private static final String SUBTOPIC = "!";
private static final char SUBTOP= SUBTOPIC.charAt(0);
private static final String INPUT = "hw3.in";
//private static final String INPUT = "input.txt";
private static class Section
public String name;
public int start = -1;
public int end = -1;
//public int page;
private LinkedList pages = new LinkedList();
//constructor
public Section(String name, int start, int end, int page)
this.name = name;
this.start = start;
this.end = end;
if(page >= 0) //this is for error checking
addPage(page);
public void addPage(int page)
pages.add(new Integer(page));
public boolean isValid()
return (start >= 0 && end >= 0 && pages.size() == 0) || pages.size() > 0;
// allows the pages to be printed out
public String toString()
String concat = "";
String szName = name;
while(name.indexOf(SUBTOPIC) >= 0) // returns tbe index of the first occurrence of the character. it takes a string or character as input parameter
concat += " ";
name = name.substring(name.indexOf(SUBTOPIC) +1);
} //end of while
concat += name + ": ";
if (start >= 0)
concat += String.valueOf(start);
if (end >= 0 && end != start)
concat += "-" +end;
else if (end >= 0)
concat += String.valueOf(end);
else
Iterator iterator = pages.iterator();
while (iterator.hasNext())
concat += iterator.next() + ", ";
if (end < concat.length())
concat= concat.substring(0, concat.length()-2);
return concat;
public static void main(String[] args)
try
FileReader fr = new FileReader(INPUT);
BufferedReader inFile = new BufferedReader(fr);
TreeMap map = new TreeMap(
new Comparator()
public int compare(Object o1, Object o2)
String s1= (String) o1;
String s2= (String) o2;
s1.replace(SUBTOP, ' ');
s2.replace(SUBTOP, ' ');
s1.toLowerCase();
s2.toLowerCase();
return s1.compareTo(s2);
//return s1.compareToIgnoreCase(s2); //Compares two strings lexicographically, ignoring case considerations.
public boolean equals(Object obj)
return false;
String line = null;
for (int i = 0; (line = inFile.readLine()) != null; i++)
StringTokenizer st = new StringTokenizer(line, "{}");
//if (st.countTokens() != 4)
//System.err.println("Error, Please correct: '" +line +"'");
//continue;
st.nextToken();
String name= st.nextToken();
st.nextToken();
String szPage= st.nextToken();
int start= -1;
int end= -1;
int page= -1;
if (name.endsWith(START))
name= name.substring(0, name.length() -START.length());
start= Integer.parseInt(szPage);
else if (name.endsWith(END)) //string built in function endsWith()
name= name.substring(0, name.length() - END.length());
end= Integer.parseInt(szPage);
else
page = Integer.parseInt(szPage); //convet the string into integers
Section section = (Section) map.get(name); //???????????
if (section == null) //if object section is null, create new section object and initialize
section = new Section(name, start, end, page); //start cannot be omitted
map.put(name, section);
else if (start >= 0) //if more pages under
section.start= start;
else if (end >= 0) //if more pages under same heading are found
section.end = end; // overwrite ???
else if (page >= 0) //if there are more pages under the same heading add a page. euler s constant
section.addPage(page);
fr.close(); //close the input stream
System.out.println("\nIndex:");
ArrayList invalid= new ArrayList(); // prevents marginal occurences of repetitive header lines
Iterator sections= map.values().iterator();
while (sections.hasNext())
Section section= (Section) sections.next();
if (section.isValid())
System.out.println(" " + section);
else
invalid.add(section);
catch(FileNotFoundException exception)
{ System.err.println("File not found"); }
catch (IOException exception)
{ System.out.println(exception); }
}// end of main
// public void
} // end of class index generator
I'm even offering the buy the program to make it more proffessional...the payment is as much duke dollars as i can give...We can also negotiate on e bay using real dollars, but the assignemtn is due tonite and i don t have much time... If someone will most kindly take a look, i will be greatly indebted and humbled...isn t there anyone on this site who actually loves solving this kinda stuff?actually, your solution was how I found about this forum. go to google,
type in "index a textbook" + java, the forum pops up. Your solution has helped me a lot, I based my assignment on yours, just look at my main file. The difference was, I had to use a tree. That was more confusing than a linked list. -
Using depth first traversal to add a new node to a tree with labels
Hello,
I'm currently trying to work my way through Java and need some advice on using and traversing trees. I've written a basic JTree program, which allows the user to add and delete nodes. Each new node is labelled in a sequential order and not dependent upon where they are added to the tree.
Basically, what is the best way to add and delete these new nodes with labels that reflect their position in the tree in a depth-first traversal?
ie: the new node's label will correctly reflect its position in the tree and the other labels will change to reflect this addition of a new node.
I've searched Google and can't seem to find any appropriate examples for this case.
My current code is as follows,
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
import javax.swing.tree.*;
public class BasicTreeAddDelete extends JFrame implements ActionListener
private JTree tree;
private DefaultTreeModel treeModel;
private JButton addButton;
private JButton deleteButton;
private int newNodeSuffix = 1;
public BasicTreeAddDelete()
setTitle("Basic Tree with Add and Delete Buttons");
DefaultMutableTreeNode rootNode = new DefaultMutableTreeNode("Root");
treeModel = new DefaultTreeModel(rootNode);
tree = new JTree(treeModel);
JScrollPane scrollPane = new JScrollPane(tree);
getContentPane().add(scrollPane, BorderLayout.CENTER);
JPanel panel = new JPanel();
addButton = new JButton("Add Node");
addButton.addActionListener(this);
panel.add(addButton);
getContentPane().add(panel, BorderLayout.SOUTH);
deleteButton = new JButton("Delete Node");
deleteButton.addActionListener(this);
panel.add(deleteButton);
getContentPane().add(panel, BorderLayout.SOUTH);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setSize(400, 300);
setVisible(true);
public void actionPerformed(ActionEvent event)
DefaultMutableTreeNode selectedNode = (DefaultMutableTreeNode)tree.getLastSelectedPathComponent();
if(event.getSource().equals(addButton))
if (selectedNode != null)
// add the new node as a child of a selected node at the end
DefaultMutableTreeNode newNode = new DefaultMutableTreeNode("New Node" + newNodeSuffix++);
treeModel.insertNodeInto(newNode, selectedNode, selectedNode.getChildCount());
//make the node visible by scrolling to it
TreeNode[] totalNodes = treeModel.getPathToRoot(newNode);
TreePath path = new TreePath(totalNodes);
tree.scrollPathToVisible(path);
else if(event.getSource().equals(deleteButton))
//remove the selected node, except the parent node
removeSelectedNode();
public void removeSelectedNode()
DefaultMutableTreeNode selectedNode = (DefaultMutableTreeNode)tree.getLastSelectedPathComponent();
if (selectedNode != null)
//get the parent of the selected node
MutableTreeNode parent = (MutableTreeNode)(selectedNode.getParent());
// if the parent is not null
if (parent != null)
//remove the node from the parent
treeModel.removeNodeFromParent(selectedNode);
public static void main(String[] arg)
BasicTreeAddDelete basicTree = new BasicTreeAddDelete();
} Thank you for any help.> Has anybody got any advice, help or know of any
examples for this sort of problem.
Thank you.
Check this site: http://www.apl.jhu.edu/~hall/java/Swing-Tutorial/Swing-Tutorial-JTree.html -
Traversing JTree using DepthFirstEnumeration
Hi Java gurus,
I am working on a problem related to traversing a JTree. It is currently doing a BreadthFirstEnumeration ( as i understand) due to which i guess it is searching for the "search string" at all nodes of the 1st level of hierarchy then goes to second level and search all nodes then goes to third level of hierarchy etc.
i want to make it work in the "DepthFirstEnumeration " fashion where it comes to first node of 1st level, check all its children to match the "search string", then go to first child check all its children etc.... the come out and go to second node of the first level and repeate the traversing through its children process again just lik ethe first node.....
the cod ei have written for BreadthFirstEnumeration is as follows:
public void find(String searchString, boolean OptionGroupsOnly){
try{
if (searchString == null){
searchString = "";
searchString = searchString.toUpperCase();
if (!this.searchString.equals(searchString) || breadthFirst == null){
this.breadthFirst = root.breadthFirstEnumeration();
this.searchString = searchString;
this.treePaths = new ArrayList();
while (breadthFirst.hasMoreElements()){
OGTreeNode searchNode = (OGTreeNode)breadthFirst.nextElement();
Object userObject = searchNode.getUserObject();
if (userObject != null && searchNode.toString().toUpperCase().lastIndexOf(searchString)!= -1 && (!OptionGroupsOnly || userObject instanceof OptionGroupBean)){
if (statusPanel != null){
statusPanel.setMessage("Option/Group Found");
TreePath tp = new TreePath(searchNode.getPath());
this.setExpandsSelectedPaths(true);
this.scrollPathToVisible(tp);
this.treePaths.add(tp);
TreePath[] treePathsArrray = new TreePath[1];
treePathsArrray = (TreePath[])treePaths.toArray(treePathsArrray);
this.setSelectionPaths( (TreePath[])treePaths.toArray(treePathsArrray));
return;
breadthFirst=null;
if (statusPanel != null){
statusPanel.setMessage("Find Complete");
JOptionPane.showMessageDialog(null, "Find Complete." );
}catch(Exception e){
Logger.getLogger(APPLOGGER).log(Level.WARNING, e.toString(), e);
can you suggest any change in the code???Did you look at the [url http://java.sun.com/j2se/1.4.2/docs/api/javax/swing/tree/DefaultMutableTreeNode.html#method_summary]API for DefaultMutableTreeNode and see if there were any other methods that returned an enumeration?
Maybe you are looking for
-
HELP Help needed to update a 4th gen ipod touch running version 4.3.5 (8L1) to the latest 6.0 version. When I connect and try to update i keep getting a box which states that a connection error occured and I cannot update. I have been given a new la
-
How to flip through multiple image files in a folder using Preview?
On windows a default image viewing program similar to preview allows a user to press the arrow keys to flip through images within the same folder as the image file originally opened with a Preview-like application. How can a person filp through image
-
I have an iPhone 3GS and the screen is very dim. Anyone know how to fix it?
-
My wife and I both have Macs that connect to a Wi-Fi router which we have connected to our cable service. An alternative Wi-Fi source is supplied to our building, that is slower, and which requires us to go to an "accept" screen every couple of we
-
Photoshop Elements 8: Watch Folder on Network Drive
I have all my photos on a network drive, I am trying to access via this computer and every time I add the folder to the watched folder, it says "access is denied". What is the proper way to add photos from a network device? Thanks Jim