Java tree beginner questions? -
today told create tree data structure below class,
public class node(){ private string lable; private list<node> children; }
after started create tree, struck @ first.
it contains node inside node. totally confused. well, tree maybe familiar you. may think whats this! clear. how getting confused
that.
for me, first time trying create tree in java. honest, used setters , getters inside class in java. these methods, cannot think of inserting new nodes after first level.
i have seen examples in google , many in stackoverflow. beginner(in tree) me looks incomplete. may may thought, op can continue that.
if explain me concept , how add more children, generic example appreciative.
update:
it may weired you, how started @ beginning.
node node = new node(); string label = "bikes"; arraylist<node> children = new arraylist<node>(); node childnode = new node(); childnode.setlabel("yamaha"); children.add(childnode); childnode = new node(); childnode.setlabel("suzuki"); children.add(childnode); childnode = new node(); childnode.setlabel("honda"); children.add(childnode); node.setlabel(label); node.setchildren(children);
after that, told cannot think next level. after doing searches have found having method addchild()
then created mine,
public void addchildren(node node){ children.add(node); }
i continued this,
arraylist<node> children = new arraylist<node>(); node.setlabel(label); node.addchildren(node);
now again strucked here. again cannot think of adding more branches root node. hope makes clear.
first drop () in class name:
should be:
public class node { ....
edit
i press sumbit before time. here's complete answer ( hint: can undo downvote :p )
they called trees , because 1 branch may either have leafs or other branches.
that's why node may have other nodes inside.
when node doesn't have children, in leaf. when branch.
so, this:
import java.util.*; // existing code: class node { private string label; private list<node> children = new arraylist<node>(); // here's how build 1 strucure public static void main( string ... args ) { node 1 = new node(); one.label = "1"; node 2 = new node(); two.label = "2"; node root = new node(); root.label = "plus"; root.children.add( 1 ); root.children.add( 2 ); print( root ); } // here's how you'll print values static void print( node node ) { system.out.println( node.label ); for( node child : node.children ) { // if child branch if( child.children.size() > 0 ) { // print branch ( recursively ) print( child ); } else { // leaf, print label. system.out.println( "-- ["+child.label+"]" ); } } } }
that root node ( "plus" ) has 2 childs ( "1" , "2" ) nodes in turn may have other nodes ( that's not case here ) tree does.
i hope you.
Comments
Post a Comment