java - Depth first search list paths to all end nodes -
hi have tree in paths initial (root) node leaves.
i found several algortithms list (all) apths betwenn given 2 nodes within graph (for example question: graph algorithm find connections between 2 arbitrary vertices)
for binary tree there exists algorithm http://techieme.in/print-all-paths-in-a-tree/ work on tree various branching factors.
is there better way of achieving want traversing tree once in order leaves , run algorithm above leaves combined initial node?
i thinking implementing simple dfs extended additional stack containing nodes alongt path single leaf , listing sentences looping through these stacks.
arraylist<grammarnode> discovered = new arraylist<grammarnode>(); stack<grammarnode> s = new stack<grammarnode>(); while (!s.empty()) { node = s.pop(); if (!discovered.contains(node)) { discovered.add(node); system.out.println(node.getword.getspelling().trim()); (grammararc arc : node.getsuccessors()) { s.push(arc.getgrammarnode()); } } }
update: problem of 1 has alyways go root in order generate full sentences. guess question is: how remember node visited (this means children nodes explored)?
printing paths root every leaf mean print entire tree i'd use simple dfs , following each node:
- add list/stack
- if node has children, repeat children
- if node leaf, print list/stack
- pop node list/stack
example:
/ \ b e / \ / \ c d f g
the first steps this:
- put on list -> {a}
- put b on list -> {a,b}
- put c on list -> {a,b,c}
- since c leaf, print list (a,b,c)
- remove c list -> {a,b}
- put d on list -> {a,b,d}
- since d leaf, print list (a,b,d)
- ...
Comments
Post a Comment