2

Can someone point me to the standard, tested, simple Tree implementation in Java?

For example, all StackOverflow searches on Java Trees lead to this topic, Tree implementation in Java (root, parents and children)

but then you discover that the Accepted Answer in that topic doesn't work and gives an Overflow Exception (https://stackoverflow.com/a/40622616/1005607) -- very dangerous, maybe someone should delete or edit that answer or at least move it down.

There are some non-StackOverflow resources but once again I don't know how reliable they are, http://programtalk.com/java/java-tree-implementation/

I find it hard to believe there's no reusable robust implementation we can go to quickly. The node should track its Parent and Children. There should be no errors.

Community
  • 1
  • 1
gene b.
  • 10,512
  • 21
  • 115
  • 227
  • I used Data Structures and-Algorithm Analysis in Java by Mark Allen Weiss ,in tree section there is a nice implementation of tree – A Sdi Dec 06 '16 at 16:13

1 Answers1

2

The problem of the question that you showed (https://stackoverflow.com/a/40622616/1005607) is that the methods addChild and setParent calls each other in an infinite loop.

public void setParent(Node<T> parent) {
    parent.addChild(this);  // Call addChild
    this.parent = parent;
}

public void addChild(Node<T> child) {
    child.setParent(this);   // Call setParent
    this.children.add(child);
}

You need to modify it as follow:

// Make this method private
private void setParent(Node<T> parent) {
    // Remove this line to prevent the loop
    // parent.addChild(this);
    this.parent = parent;
}

public void addChild(Node<T> child) {
    child.setParent(this);
    this.children.add(child);
}
Community
  • 1
  • 1
Davide Lorenzo MARINO
  • 26,420
  • 4
  • 39
  • 56