How to traverse a tree(input) and build another tree based on the certain condition?

Steven Ni
Steven Ni used Ask the Experts™
If the file system is the input tree, what I would like to do is to start from one folder, and scan each file within this folder and use the file name to search another place in the file system using some conditions like: filename = foldername, for each foldetname returned in this search, add this foldetname as a child to the output tree and search again until not more match.

So the input is a tree and output is also a tree. Recursion is what I think is required to solved the problem and hopefully someone can share ideas or examples or links , really appreciate!
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
Maybe you're looking for a structure like this (in pseudo-code):

Tree scan(File folder) {
   Tree result = new Tree() ;
   List<File> files = folder.list() ;   // This is where you "scan the input tree"
   for (File file : files) {
      if (condition(file)) {
          Tree subtree = scan(file) ;
           result.add(subtree) ;   // Need to insert this in the correct part of the tree
   return tree ;

Open in new window

If you have no way to retrieve a list of files inside a folder from a folder object, then you'd also want to pass in the input tree.  So it would be:

Tree scan(File folder, Tree input) {

and you just pass the input tree around as well.

Any help?



Thanks for the solution and sorry for the late reply as was on vacation.

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial