Here's some pseudocode. The idea is simple: Start with all the nodes unmarked, and mark your current node's parent, its parent, and so on till you reach the root. By doing this, you'll have marked exactly the nodes on the path from your current node to the root. Then you can simply print all the nodes in another pass, recursing only on "marked" nodes. This is optimal (running time is at most the number of nodes you have to print).
for all n: mark[n]=False
n=current
while n!=root:
n=parent[n]
mark[n]=True
def print_tree(n):
print_node(n)
if mark[v]==True:
print '<ul>'
for each child c of n: print_tree(c)
print '</ul>'
def print_node(n):
if n==current: print '<li class="current">' else: print '<li>'
print name[n]
print "</li>"
print_tree(root)
parent[n]
and name[n]
are probably something like n.parent
and n.name
in your structure. About the "for each child of n" part -- I presume you have an adjacency list maintaining the list of all the children of a given node. (If you don't, then what's the order in which the children should be printed?) In any case, the adjacency lists can be built in time O(number of nodes) by simply adding each node to the "children" list of its parent. The total size of the lists is at most the number of nodes (since each node other than the root occurs in exactly one of the lists) so these lists don't take much memory (a single list might contain a lot of elements, but the total size is bounded).