1

I have an ArrayList<Foo> structure in Java with standard tree-like fields: id, id_parent, value

I want to get a list of all leaves (id_element's) of a given node.

My example data is:

Foo ArrayList<E>
    elementData Object[10]
        [0] Foo
            id          1333393146
            id_element  1333398441937
            id_parent   1333393120
            value       "1.1."
        [1] Foo
            id          1333393120
            id_element  0
            id_parent   0
            value       "1."
        [2] Foo
            id          1333400050
            id_element  0
            id_parent   0
            value       "2."
        [3] Foo
            id          1333400480
            id_element  0
            id_parent   1333400050
            value       "2.1."
        [4] Foo
            id          1333400596
            id_element  1335957085269
            id_parent   1333400480
            value       "2.1.1."
        [5] Foo
            id          1333401059
            id_element  1335957088564
            id_parent   1333400480
            value       "2.1.2."
        [6] Foo
            id          1333401973
            id_element  1335957090492
            id_parent   1333400480
            value       "2.1.3."
        [7] Foo
            id          1333401974
            id_element  1335957093220
            id_parent   1333400050
            value       "2.2."
        [8] Foo
            id          1333392031
            id_element  0
            id_parent   0
            value       "3."
        [9] Foo
            id          1333394672
            id_element  1335957098326
            id_parent   1333392031
            value       "3.1."

I need to do a function public ArrayList<Long> GetIds(ArrayList<Foo> tree, Long id_node) { } where tree is my structure, and id_node is an id of a node.

I need only parent node leaves not child nodes.

e.g.:


input: [above structure], id = 1333400050

output: 1335957085269, 1335957088564, 1335957090492, 1335957093220


I do not know why I have a blackout about this..

radzi0_0
  • 1,250
  • 2
  • 14
  • 24

1 Answers1

4
public static ArrayList<Long> getIds(ArrayList<Foo> tree, Long id_node) {
    ArrayList<Long> leaves = new ArrayList<Long>();
    for (Foo foo : tree) {
        if (foo.id_parent == id_node) {
            ArrayList<Long> ids = getIds(tree, foo.id);
            if (ids == null) {
                leaves.add(foo.id);
            } else {
                leaves.addAll(ids);
            }
        }
    }
    if (leaves.isEmpty()) {
        return null;
    }
    return leaves;
}
Jimi Kimble
  • 504
  • 5
  • 10