How to get all the leaves of a given node? (the tree has only id_parent)

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

I want to get a list of all the sheets ( id_element 's) of this node.

My example data:

 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 execute the public ArrayList<Long> GetIds(ArrayList<Foo> tree, Long id_node) { } function public ArrayList<Long> GetIds(ArrayList<Foo> tree, Long id_node) { } , where tree is my structure and id_node is the node identifier.

I only need a parent node that does not contain child nodes.

eg:.




input: [above structure], id = 1333400050

: 1335957085269, 1335957088564, 1335957090492, 1335957093220




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

+1
java algorithm hierarchical-data tree nodes
May 2 '12 at 11:57
source share
1 answer
 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; } 
+4
May 2 '12 at 12:25
source share



All Articles