I have a non-binary tree.
I want to find all "sub-trees" that are connected to root.
Sub-tree is a a link group of tree nodes.
enter image description here
every group is colored in it's own color.
What would be be the best approach? Run recursion down and up for every node?
The data structure of every treenode is a list of children, list of parents. (the type of children and parents are treenodes)
Clarification:
Group defined if there is a kind of "closure" between nodes where root itself is not part of the closure.
As you can see from the graph you can't travel from pink to other nodes (you CAN NOT use root).
From brown node you can travel to it's child so this form another group.
Finally you can travel from any cyan node to other cyan nodes so the form another group
-
Are you looking for just the child trees of the root, or all descendents?Andy Hunt– Andy Hunt2012年01月10日 09:59:45 +00:00Commented Jan 10, 2012 at 9:59
-
yes,child trees of the rootkenny– kenny2012年01月10日 10:50:59 +00:00Commented Jan 10, 2012 at 10:50
-
1Kenny, please add any clarifications to the question itself (edit & update) and not in comments.yannis– yannis2012年01月10日 12:22:52 +00:00Commented Jan 10, 2012 at 12:22
-
9The thing in the picture is not a tree. Tree ≡ graph without circles. Your graph has circles (if it didn't the answer would have been trivial).Jan Hudec– Jan Hudec2012年01月10日 12:50:20 +00:00Commented Jan 10, 2012 at 12:50
-
2So what you want is connected components after removal of root. Well, that should give you the algorithm.Jan Hudec– Jan Hudec2012年01月10日 12:58:47 +00:00Commented Jan 10, 2012 at 12:58
1 Answer 1
You could use a BFS algorithm (a graph algorithm explained on Wikipedia), starting from the node you want to make root.
The algorith behaves like this:
procedure BFS(G,v,btree):
create a queue Q
enqueue v onto Q
mark v
btree = new Tree(v);//Create a tree structure with v as root
while Q is not empty:
t ← Q.dequeue()
btree.add(t) // Here its where you add elements to your tree
for all edges e in G.incidentEdges(t) do
o ← G.opposite(t,e)
if o is not marked:
mark o
enqueue o onto Q
When Q is empty means you processed all the possible nodes and all of them have been added to your binary tree (btree).
Once you have your btree you can apply any simple algorithm to obtain what you need
-
What exactly do you mean by Graph.opposite(Vertex, Edge): Vertex?Jan Hudec– Jan Hudec2012年01月10日 14:50:08 +00:00Commented Jan 10, 2012 at 14:50
-
@Jan_Hudec The node in the other side of the edge. I mean, each vertex has two sides, the one your are standing and the one you are not ( lets imagine its not an edge to ourself) Edge y --- Vertex ---- Edge o , so that way you have the vertex on the "opposite" side of the edgeguiman– guiman2012年01月10日 14:57:20 +00:00Commented Jan 10, 2012 at 14:57
-
An, normally I'd just either say e.second, or for all u: (t, u) in E(G). Anyway.Jan Hudec– Jan Hudec2012年01月10日 15:14:39 +00:00Commented Jan 10, 2012 at 15:14