1

Please find a Tree class definition below.

public class Tree<T>{

  private T head;

  private List<Tree<T>> leafs = new ArrayList<>();

  private Tree<T> parent = null;

  private Map<T, Tree<T>> locate = new HashMap<>();

  public Tree(T head) {
    this.head = head;
    locate.put(head, this);
  }


  public void addLeaf(T root, T leaf) {
    if (locate.containsKey(root)) {
     locate.get(root).addLeaf(leaf);
    } else {
      addLeaf(root).addLeaf(leaf);
    }
  }

  public Tree<T> addLeaf(T leaf) {
    Tree<T> t = new Tree<>(leaf);
    leafs.add(t);
    t.parent = this;
    t.locate = this.locate;
    locate.put(leaf, t);
    return t;
  }
}

The Tree class object is created in another class and nodes are added in a straightforward way (using the addLeaf(node) function). This process builds the tree alright. Would someone be able to suggest a DFS function implementation on the constructed tree adhering to the above class definition?

Thank you.


This is what I've tried. Yes, it gives me meaningless results.

protected void DFS() {
    for(Tree<T> child : leafs) {
        DFS();
        System.out.println(child);
    }
}

The code is from the third comment at link


protected void DFS() {
  for(Tree<T> child : leafs) {
      child.DFS();
      System.out.println(child.head);
  }
}

resolved!

Community
  • 1
  • 1
leba-lev
  • 2,788
  • 10
  • 33
  • 43
  • Homework? SO is not a "give me teh codez" site. What have you tried? – Jim Garrison Mar 07 '12 at 20:44
  • 1
    `leafs` should be `leaves` -- surely you didn't mean the [Maple Leafs](http://mapleleafs.nhl.com/) :) – Marvin Pinto Mar 07 '12 at 20:45
  • @JimGarrison This is the first time for me with implementing trees. I'm trying to understand the process in a top-down manner, since I couldn't find tutorials which sufficiently support the bottom-up learning process. – leba-lev Mar 07 '12 at 21:01
  • 1
    https://en.wikipedia.org/wiki/Depth_first_search – Jochen Mar 07 '12 at 21:09

1 Answers1

2

You're close. The print should be the value of the node, and the recursion should be on the child.

kevingallagher
  • 908
  • 1
  • 8
  • 9