![]() |
|
![]() |
|
|
Thread Tools | Display Modes |
|
|
#1 |
|
Newbie
Join Date: Apr 2005
Posts: 2
Rep Power: 0
![]() |
Hi,
I have the following sample data in a table in MySQL. a level 1 35 b level 2 a 34 c level 2 a 33 d level 3 b 32 e level 3 b 31 f level 3 c 30 g level 3 c 29 h level 4 d 28 i level 4 d 27 j level 4 e 26 Basically, the third column points to the first column. I need to develop an algorithm which finds all the leaf nodes in the table. I know it must be recursive, but I simply can't do it! Thanks! |
|
|
|
|
|
#2 |
|
Programming Guru
![]() |
can you possibly explin the data a bit more?
|
|
|
|
|
|
#3 |
|
I eat cake for breakfast.
![]() ![]() ![]() ![]() Join Date: Jul 2004
Location: In my box.
Posts: 4,434
Rep Power: 9
![]() |
I think I get it. Including headers, it would be:
ID | Level | Parent | Data ----+-------+--------+-------- a | 1 | | 35 b | 2 | a | 34 c | 2 | a | 33 d | 3 | b | 32 e | 3 | b | 31 f | 3 | c | 30 g | 3 | c | 29 h | 4 | d | 28 i | 4 | d | 27 j | 4 | e | 26 struct data
{
int ID;
data *childLeft;
data *childRight;
string data;
}
data nodes [10]; |
|
|
|
|
|
#4 |
|
Professional Programmer
Join Date: Nov 2004
Posts: 250
Rep Power: 4
![]() |
>(or whatever you call them in Java)
Classes. ![]() >I'm not sure how they work in Java Java references work pretty much the same as C++ pointers. The only real difference is that references in Java are more restricted than C++ pointers. The equivalent code in Java would be: class Node {
public int ID;
public String data;
public Node left, right;
}
Node[] nodes = new Node[10];The table represents a tree structure. You can either build the tree and then traverse it to find leaves, or process the table such that any ID that is not a parent is a leaf. Simple code to do that follows: char[] IDs;
char[] parents;
// Fill IDs and parents with the corresponding table values
char[] leaves = new char[IDs.length]; // Too big, but better than too small
int k = 0;
for ( int i = 0; i < IDs.length; i++ ) {
int j;
// Seach for IDs[i] in the parents list
for ( j = 0; j < parents.length; j++ ) {
if ( parents[j] == IDs[i] )
break;
}
// Not found, must be a leaf
if ( j == parents.length )
leaves[k++] = IDs[i];
} |
|
|
|
|
|
#5 |
|
Newbie
Join Date: Apr 2005
Posts: 2
Rep Power: 0
![]() |
Thanks for all your help.
I solved the problem by creating an array, and traversing the tree and storing each node in the array. Once I had all the nodes in the array, I traversed the array and check whether or not that node was a parent to any other node. If it returned nothing, it means that it's a leaf node. |
|
|
|
![]() |
| Bookmarks |
| Currently Active Users Viewing This Thread: 1 (0 members and 1 guests) | |
| Thread Tools | |
| Display Modes | |
|
|