473,545 Members | 1,779 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Advanced: Populating, Printing Tree Structure

Been banging my head on this for two days now. Hope someone can help!

My test program below is in the form of a single JSP, with a Node class
build in. (All the coded needed to run is below.)
The technical requirements:

1) Store tree data in the database so that it can be
extracted as a tree structure. For test purposes,
I'm mimicking this table structure in the code
with a Vector of HashMaps (where each HashMap represents
one row from the java.sql.result Set).

The tree data is returned from the resultSet as follows:

ID PARENT_ID DESC
---------------------------------------
10 null Node A
100 10 Leaf A1
101 10 Leaf A2
102 10 Leaf A3

20 null Node B

30 null Node C
300 30 Leaf C
301 30 Leaf C1

2) Using the above resultSet format, draw the tree contents to web
browser (NOT using applets or swing, just as a string of HTML).

The tree structure string will look as follows, supporting 'n'
levels deep:
Node A
Leaf A1
Leaf A2
Node A1
Leaf A1a
Leaf A3

Node B

Node C
Leaf C1
Leaf C2


Below is the mostly-working (?) code. I believe the tree is populated
correctly using recursion, but it could very well be screwed up. It's
difficult to tell because I've been unable to traverse the populated tree
structure and print its contents.

Can someone take a look at this and see if 1) the tree is populated
correctly, and 2) help me to correctly print the formatted tree (as shown
above, nothing fancy).

Any design improvements are also welcome! I believe some or all of the
member variables can be eliminated.

The method setNodeList() populates the tree strucure, and printTree() is
then supposed to print the contents of the tree.

Thanks a bunch if you can help out, this is driving me nuts!

BEGIN JSP CONTENT

<%!
ArrayList rootList = new ArrayList();

public Node findNode( Integer nodeID, ArrayList nodeList )
{
for( int j = 0; j < nodeList.size() ; j++ )
{
Node node = (Node)nodeList. get(j);
HashMap dataRow = (HashMap)node.g etObject();
Integer currID = (Integer)dataRo w.get("ID");

if( nodeID.equals(c urrID) )
{
return node;
}

findNode( nodeID, node.getChildLi st() );
}

return null; //couldn't find node
}
public void setNode( HashMap dataRow )
{
Node node = new Node(dataRow);
Integer parentID = (Integer)dataRo w.get( "PARENT_ID" );

Node parentNode = findNode( parentID, rootList );

if( parentNode != null )
{
parentNode.addC hild(node);
}
else
{
rootList.add(no de);
}
}

public void setNodeList( Vector dataRowList )
{
for( int j = 0; j < dataRowList.siz e(); j++ )
{
HashMap dataRow = (HashMap)dataRo wList.elementAt (j);
setNode( dataRow );
}
}
void printTree( Node node, int indentation )
{
for( int i=0; i<3*indentation ; i++ )
System.out.prin t(" ");

ArrayList childNodeList = node.getChildLi st();
for( int j = 0; j < childNodeList.s ize(); j++ )
{
Node tempNode = (Node)childNode List.get(j);

HashMap dataRow = (HashMap)tempNo de.getObject();
String desc = (String)dataRow .get("DESC");

System.out.prin tln( desc );

preorderDisplay ( tempNode, ++indentation );
}
}

/*
* Sample java.sql.result Set format:
*
* ID PARENT_ID DESC
* ---------------------------------------
* 10 null Node A
* 100 10 Leaf A1
* 101 10 Leaf A2
* 102 10 Leaf A3
*
* 20 null Node B
*
* 30 null Node C
* 300 30 Leaf C1
* 301 30 Leaf C2
*
*/
private Vector getTestDataRowL ist()
{
HashMap row1=getRow(new Integer(10), new Integer(-1), "Node A");
HashMap row2=getRow(new Integer(100), new Integer(10), "Leaf A1");
HashMap row3=getRow(new Integer(101), new Integer(10), "Leaf A2");
HashMap row4=getRow(new Integer(102), new Integer(10), "Leaf A3");

HashMap row5=getRow(new Integer(20), new Integer(-1), "Node B");

HashMap row6=getRow(new Integer(30), new Integer(-1), "Node C");
HashMap row7=getRow(new Integer(300), new Integer(30), "Leaf C1");
HashMap row8=getRow(new Integer(301), new Integer(30), "Leaf C2");

Vector dataRowList = new Vector();

dataRowList.add (row1);
dataRowList.add (row2);
dataRowList.add (row3);
dataRowList.add (row4);
dataRowList.add (row5);
dataRowList.add (row6);
dataRowList.add (row7);
dataRowList.add (row8);

return dataRowList;
}
private HashMap getRow( Integer id, Integer parID, String desc )
{
HashMap dataRow = new HashMap();
dataRow.put( "ID", id );
dataRow.put( "PARENT_ID" , parID );
dataRow.put( "DESC", desc );
return dataRow;
}

%>


<PRE>
<%

System.out.prin tln( "\n\n\n" );

Vector dataRowList = getTestDataRowL ist();

setNodeList( dataRowList );

for( int j = 0; j < rootList.size() ; j++ )
{
Node node = (Node)rootList. get(j);
printTree( node, 0 );
}
System.out.prin tln( "\n\n\n" );

%>
TEST
</PRE>

<%!

private class Node
{
private Object obj = null;
private ArrayList childList = new ArrayList();

public Node( Object obj )
{
this.obj = obj;
}

public Object getObject()
{
return this.obj;
}

public void addChild( Node node )
{
this.childList. add(node);
}
public ArrayList getChildList()
{
return this.childList;
}
}

%>

END JSP CONTENT

Jul 17 '05 #1
3 14019
Hi Steve,

have you looked at the javax.swing.tre e package. I know it's not a swing
application but the tree model framework is already in place, no need to
reinvent the wheel.

DefaultTreeMode l
DefaultMutableT reeNode

Build up the tree from the database resultset. This might be worth
looking at.

From a general design point of view you could make better use of the
Collections framework:

YOUR CODE:

public Node findNode( Integer nodeID, ArrayList nodeList )
{
for( int j = 0; j < nodeList.size() ; j++ )
{
Node node = (Node)nodeList. get(j);
HashMap dataRow = (HashMap)node.g etObject();
Integer currID = (Integer)dataRo w.get("ID");

if( nodeID.equals(c urrID) )
{
return node;
}

findNode( nodeID, node.getChildLi st() );
}

return null; //couldn't find node
}

SUGGESTION:

public Node findNode( Integer nodeID, Collection nodeList )
{
Iterator iter = nodeList.iterat or();
while (iter.hasNext() )
{
Node node = (Node)iter.next ();
Map dataRow = (Map)node.getOb ject();
Integer currID = (Integer)dataRo w.get("ID");

if( nodeID.equals(c urrID) )
{
return node;
}

findNode( nodeID, node.getChildLi st() );
}

return null; //couldn't find node
}
This allows you to change the implementation (ArrayList -> LinkedList,
HashMap -> TreeMap) without having to change the rest of your code.

Good Luck,
Barry

Steve Johnson wrote:
Been banging my head on this for two days now. Hope someone can help!

My test program below is in the form of a single JSP, with a Node class
build in. (All the coded needed to run is below.)
The technical requirements:

1) Store tree data in the database so that it can be
extracted as a tree structure. For test purposes,
I'm mimicking this table structure in the code
with a Vector of HashMaps (where each HashMap represents
one row from the java.sql.result Set).

The tree data is returned from the resultSet as follows:

ID PARENT_ID DESC
---------------------------------------
10 null Node A
100 10 Leaf A1
101 10 Leaf A2
102 10 Leaf A3

20 null Node B

30 null Node C
300 30 Leaf C
301 30 Leaf C1

2) Using the above resultSet format, draw the tree contents to web
browser (NOT using applets or swing, just as a string of HTML).

The tree structure string will look as follows, supporting 'n'
levels deep:
Node A
Leaf A1
Leaf A2
Node A1
Leaf A1a
Leaf A3

Node B

Node C
Leaf C1
Leaf C2


Below is the mostly-working (?) code. I believe the tree is populated
correctly using recursion, but it could very well be screwed up. It's
difficult to tell because I've been unable to traverse the populated tree
structure and print its contents.

Can someone take a look at this and see if 1) the tree is populated
correctly, and 2) help me to correctly print the formatted tree (as shown
above, nothing fancy).

Any design improvements are also welcome! I believe some or all of the
member variables can be eliminated.

The method setNodeList() populates the tree strucure, and printTree() is
then supposed to print the contents of the tree.

Thanks a bunch if you can help out, this is driving me nuts!

BEGIN JSP CONTENT

<%!
ArrayList rootList = new ArrayList();

public Node findNode( Integer nodeID, ArrayList nodeList )
{
for( int j = 0; j < nodeList.size() ; j++ )
{
Node node = (Node)nodeList. get(j);
HashMap dataRow = (HashMap)node.g etObject();
Integer currID = (Integer)dataRo w.get("ID");

if( nodeID.equals(c urrID) )
{
return node;
}

findNode( nodeID, node.getChildLi st() );
}

return null; //couldn't find node
}
public void setNode( HashMap dataRow )
{
Node node = new Node(dataRow);
Integer parentID = (Integer)dataRo w.get( "PARENT_ID" );

Node parentNode = findNode( parentID, rootList );

if( parentNode != null )
{
parentNode.addC hild(node);
}
else
{
rootList.add(no de);
}
}

public void setNodeList( Vector dataRowList )
{
for( int j = 0; j < dataRowList.siz e(); j++ )
{
HashMap dataRow = (HashMap)dataRo wList.elementAt (j);
setNode( dataRow );
}
}
void printTree( Node node, int indentation )
{
for( int i=0; i<3*indentation ; i++ )
System.out.prin t(" ");

ArrayList childNodeList = node.getChildLi st();
for( int j = 0; j < childNodeList.s ize(); j++ )
{
Node tempNode = (Node)childNode List.get(j);

HashMap dataRow = (HashMap)tempNo de.getObject();
String desc = (String)dataRow .get("DESC");

System.out.prin tln( desc );

preorderDisplay ( tempNode, ++indentation );
}
}

/*
* Sample java.sql.result Set format:
*
* ID PARENT_ID DESC
* ---------------------------------------
* 10 null Node A
* 100 10 Leaf A1
* 101 10 Leaf A2
* 102 10 Leaf A3
*
* 20 null Node B
*
* 30 null Node C
* 300 30 Leaf C1
* 301 30 Leaf C2
*
*/
private Vector getTestDataRowL ist()
{
HashMap row1=getRow(new Integer(10), new Integer(-1), "Node A");
HashMap row2=getRow(new Integer(100), new Integer(10), "Leaf A1");
HashMap row3=getRow(new Integer(101), new Integer(10), "Leaf A2");
HashMap row4=getRow(new Integer(102), new Integer(10), "Leaf A3");

HashMap row5=getRow(new Integer(20), new Integer(-1), "Node B");

HashMap row6=getRow(new Integer(30), new Integer(-1), "Node C");
HashMap row7=getRow(new Integer(300), new Integer(30), "Leaf C1");
HashMap row8=getRow(new Integer(301), new Integer(30), "Leaf C2");

Vector dataRowList = new Vector();

dataRowList.add (row1);
dataRowList.add (row2);
dataRowList.add (row3);
dataRowList.add (row4);
dataRowList.add (row5);
dataRowList.add (row6);
dataRowList.add (row7);
dataRowList.add (row8);

return dataRowList;
}
private HashMap getRow( Integer id, Integer parID, String desc )
{
HashMap dataRow = new HashMap();
dataRow.put( "ID", id );
dataRow.put( "PARENT_ID" , parID );
dataRow.put( "DESC", desc );
return dataRow;
}

%>


<PRE>
<%

System.out.prin tln( "\n\n\n" );

Vector dataRowList = getTestDataRowL ist();

setNodeList( dataRowList );

for( int j = 0; j < rootList.size() ; j++ )
{
Node node = (Node)rootList. get(j);
printTree( node, 0 );
}
System.out.prin tln( "\n\n\n" );

%>
TEST
</PRE>

<%!

private class Node
{
private Object obj = null;
private ArrayList childList = new ArrayList();

public Node( Object obj )
{
this.obj = obj;
}

public Object getObject()
{
return this.obj;
}

public void addChild( Node node )
{
this.childList. add(node);
}
public ArrayList getChildList()
{
return this.childList;
}
}

%>

END JSP CONTENT


Jul 17 '05 #2
Barry White wrote:

Hi Steve,

have you looked at the javax.swing.tre e package. I know it's not a
swing application but the tree model framework is already in place, no
need to reinvent the wheel.

DefaultTreeMode l
DefaultMutableT reeNode
Yes, I have looked into those APIs, but still couldn't figure out how to
use them to any advantage with a recursive algorithm. If you have an
example of using those APIs for my scenario, that would be great.

From a general design point of view you could make better use of the
Collections framework:
[snip]
SUGGESTION:

public Node findNode( Integer nodeID, Collection nodeList )
{
Iterator iter = nodeList.iterat or();
while (iter.hasNext() )
{
Node node = (Node)iter.next ();
Map dataRow = (Map)node.getOb ject();
Integer currID = (Integer)dataRo w.get("ID");

if( nodeID.equals(c urrID) )
{
return node;
}

findNode( nodeID, node.getChildLi st() );
}

return null; //couldn't find node
}


Thanks, this sounds like a good idea.
The primary obstacle is still populating and printing that tree, and I'm
completely stuck.
Jul 17 '05 #3
Hi again,

perhaps have your node extend DefaultMutableT reeNode() and build up a
DefaultTreeMode l from the nodes. You could use a HashMap to map ID's to
nodes so you can find a parent node when you need to add a new child.

Look at:
http://java.sun.com/docs/books/tutor...tree.html#data

You coult test your code with a Swing JTree too :)

Barry
Steve Johnson wrote:
Barry White wrote:
Hi Steve,

have you looked at the javax.swing.tre e package. I know it's not a
swing application but the tree model framework is already in place, no
need to reinvent the wheel.

DefaultTreeMo del
DefaultMutabl eTreeNode

Yes, I have looked into those APIs, but still couldn't figure out how to
use them to any advantage with a recursive algorithm. If you have an
example of using those APIs for my scenario, that would be great.


From a general design point of view you could make better use of the
Collections framework:

[snip]

SUGGESTION:

public Node findNode( Integer nodeID, Collection nodeList )
{
Iterator iter = nodeList.iterat or();
while (iter.hasNext() )
{
Node node = (Node)iter.next ();
Map dataRow = (Map)node.getOb ject();
Integer currID = (Integer)dataRo w.get("ID");

if( nodeID.equals(c urrID) )
{
return node;
}

findNode( nodeID, node.getChildLi st() );
}

return null; //couldn't find node
}

Thanks, this sounds like a good idea.
The primary obstacle is still populating and printing that tree, and I'm
completely stuck.


Jul 17 '05 #4

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

2
5793
by: ragha | last post by:
Dear friends I am emulating thr tree structure mentioned in the article http://www.15seconds.com/issue/010921.htm I have succesfully created the folder structure for level 2 I need this structure till 5 level is there any easier way to generate this using xsl My xml tree node is
1
1988
by: googleo | last post by:
Hi, in my application I want to handle and store data in a hierarchic data structure. For example: persons who manage houses; houses have various numbers of floors; floors have various numbers of rooms etc. My first concept is to use a tree structure, to ideally save the whole tree to file and load from file.
1
7147
by: Srihari | last post by:
I'm trying to develop a tree structure using javascript. The node values of the tree are generating from a mysql table depending on login. The tree structure contains 3 sub levels. I developed static HTML tree using http://www.treeview.net. now i need to generate this tree dynamically. Can any one has code for this?
4
612
by: Stephan Tobies | last post by:
Hi everyone, I am looking for a good data structure that could be used to represent families of trees with shared sub-trees and copy-on-write semantics. On a very abstract level, I would like to have an API like this: Let Node be a suitably defined data structure. Then the following functions shall be supported:
1
2729
by: David Hirschfield | last post by:
I've written a tree-like data structure that stores arbitrary python objects. The objective was for the tree structure to allow any number of children per node, and any number of root nodes...and for it to be speedy for trees with thousands of nodes. At its core, the structure is just a list of lists arranged so that if node A has children...
1
2244
by: tejasnegi | last post by:
I have to print a binary structure using C. The output must be something like a b c d e f g I already have the data structure and i want to print this output tree.
5
3700
by: hankypan1 | last post by:
Hi All, I need a tree data structure for my application. It is the non -cyclic simple tree where i can have any number of children node and each child can recursively become a sub tree like a normal tree. Now the thing is i can popullate my tree at compile time like a global data. Since i know my tree definition at compile time, instead...
8
1789
by: =?ISO-8859-1?Q?m=E9choui?= | last post by:
Problem: - You have tree structure (XML-like) that you don't want to create 100% in memory, because it just takes too long (for instance, you need a http request to request the information from a slow distant site). - But you want to be able to request data from it, such has "give me all nodes that are under a "//foo/bar" tree, and have a...
0
2191
by: mac | last post by:
I found that with memory allocating techniques used nowadays (addresses alignment, eg. on 32bit machines) one can detect loops in a tree structure very fast, without using extra memory. This is due to a possibility of storing extra information in unused bits of the tree pointers (it works for linked lists too). One can say it is dangerous or...
0
7459
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main...
0
7653
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. ...
1
7411
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For...
0
7749
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the...
0
5965
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then...
0
3444
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in...
1
1871
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
1
1012
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
0
695
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.