Take the 2-minute tour ×

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)) {
    } else {

  public Tree<T> addLeaf(T leaf) {
    Tree<T> t = new Tree<>(leaf);
    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) {

The code is from the third comment at link

protected void DFS() {
  for(Tree<T> child : leafs) {


share|improve this question
Homework? SO is not a "give me teh codez" site. What have you tried? –  Jim Garrison Mar 7 '12 at 20:44
leafs should be leaves -- surely you didn't mean the Maple Leafs :) –  Marvin Pinto Mar 7 '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 7 '12 at 21:01

1 Answer 1

up vote 2 down vote accepted

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

share|improve this answer
Thank you for the pointer. –  leba-lev Mar 7 '12 at 23:10

Your Answer


