Re: hacker challenge - traverse a list
- From: Nelu <spamahead@xxxxxxxxx>
- Date: 29 Feb 2008 20:25:55 GMT
On Fri, 29 Feb 2008 17:56:24 +0000, Richard Harter wrote:
Here is a little challenge - print the contents of a binary tree in
order only using O(1) additional memory. In other words you can't use
recursion or simulate it with a stack. As far as I know you can't do
this without some kind of hack. Also AFAIK there is no way to do this
that should ever be used in real code. Rules? We don't need no
steenking rules! Use whatever language you like, though I suppose this
is a natural for C based languages. Tag bit solutions (i.e. mark a link
as visited when we go down it and unmark it when we come back up) don't
count because (a) everyone thinks of it, and (b) it (debatably) uses
O(log n) memory. Platform dependencies are okay - this a hack, after
all.
What does in order mean? Inorder?
If you just want to print the content of every node no matter what the
order of the keys is, assign an index (number) to each node (even not
existing nodes) similar to what you would have in a heap structure.
You can use a loop to print each node by its index starting with 0 (the
root). To get to the node with a certain index you can constuct the path
step by step by diving the index (-1 if zero based) by 2 and using the
result to mark the parent and the remainder specifies how to reach the
current node from the parent node (0 means left, 1 means right).
This is expensive because you have to repeat some calculations to avoid
using a queue. What you probably need in this case is a cursor (pointer
to walk the tree), variables for the current node and target node indexes
and a flag that tells you if there were any nodes printed at this depth.
If none was printed you stop the algorithm as you just ran out of
nodes :).
The indexes are assigned starting with the root and from left to right at
each depth
0
1 2
3 4 5 6
and so on...
I assume this fits the O(1) description. (This is something I just made
up so it's not tested, I just assume it works). Each depth start with a
node of index 2^depth-1 (again, even if the node doesn't really exist).
--
Ioan - Ciprian Tandau
tandau _at_ freeshell _dot_ org (hope it's not too late)
(... and that it still works...)
.
- Follow-Ups:
- Re: hacker challenge - traverse a list
- From: Richard Harter
- Re: hacker challenge - traverse a list
- References:
- hacker challenge - traverse a list
- From: Richard Harter
- hacker challenge - traverse a list
- Prev by Date: Re: Compiler Loop Unswitching
- Next by Date: Re: hacker challenge - traverse a list
- Previous by thread: Re: hacker challenge - traverse a list
- Next by thread: Re: hacker challenge - traverse a list
- Index(es):
Relevant Pages
|