data structures - How do I create a toString using another 'helper' class in my Tree java? -
i'm trying figure out how create tostring() method parentheticrepresentation class given below.
public static <e> string parentheticrepresentation(tree<e> t, position<e> v) { string s = v.element().tostring(); if (t.islnternal(v)) { boolean firsttime = true; (position<e> w : t.children(v)) if (firsttime) { s += " ( " + parentheticrepresentation(t, w); firsttime = false; } else s += ", " + parentheticrepresentation(t, w); s += " ) "; } homecoming s; } in main class, when create nodes tree, , seek output whole tree, outputs 1 node parentheticrepresenation. how create tostring() class using when phone call output tree, gives me representation in class above. help appreciated!
public static void main(string[] args) { linkedtree<character> t = new linkedtree(); // add together root t.addroot('a'); // add together children of root t.createnode('b', (treenode) (t.root()), new nodepositionlist()); treeposition c = t.createnode('c', (treenode) (t.root()), new nodepositionlist()); t.createnode('d', (treenode) (t.root()), new nodepositionlist()); // add together children of node c t.createnode('e', c, new nodepositionlist()); treeposition f = t.createnode('f', c, new nodepositionlist()); t.createnode('g', c, new nodepositionlist()); // add together childrn of node f t.createnode('h', f, new nodepositionlist()); t.createnode('i', f, new nodepositionlist()); // print out tree system.out.println("size = " + t.size()); system.out.println("here tree:"); system.out.println(t); } }
you need pre-order traversal, opening parenthesis when traverse children , closing afterwards.
something (not sure if works since didnt test it, give idea).
public static <e> string parentheticrepresentation(tree<e> t, position<e> v) { string s = ""; if (t.islnternal(v)) { s = v.element().tostring(); //adds node string if(t.children(v).size() > 0) { s += "("; //opens parenthesis children (position<e> w : t.children(v)) { s += parentheticrepresentation(t, w) + ","; } s = s.deletecharat(s.length() - 1); //deletes lastly comma s += ")"; //closes parenthesis children } } homecoming s; } to override tostring() method, add together tree class.
@override public string tostring(){ //just speculating treehelper name, calling helper method. homecoming treehelper.parentheticrepresentation(this,this.root()); } edit: using "this" reference since within tree class.
java data-structures tree linked-list
No comments:
Post a Comment