Re: hacker challenge - traverse a list
- From: Ben Pfaff <blp@xxxxxxxxxxxxxxx>
- Date: Fri, 29 Feb 2008 13:13:55 -0800
cri@xxxxxxxx (Richard Harter) writes:
On Fri, 29 Feb 2008 10:04:26 -0800, Ben Pfaff
<blp@xxxxxxxxxxxxxxx> wrote:
cri@xxxxxxxx (Richard Harter) writes:
Here is a little challenge - print the contents of a binary tree
in order only using O(1) additional memory.
Do you want to limit runtime to O(n) or forbid modifying the
binary tree? I can think of a simple solution in the latter
category, and I have the sketch of a solution in the former
category.
Is it a binary search tree or an arbitrary binary tree?
What I was thinking of was a binary tree with left and right
children links and no parent links. Obviously it is trivial if
there is a parent link.
My take is that you can modify the tree during the traversal
provided that it is in the original condition when you are done.
One way to do it would be to use the BST rebalancing algorithm
described, among other places, at:
http://adtinfo.org/libavl.html/Balancing-a-BST.html
The first step of the algorithm converts the tree into a doubly
linked list. At this point, you can traverse it in inorder. The
second step balances the tree. The algorithm runs in O(1) space
and O(n) time.
This approach will not restore the original shape of the tree,
but the new shape is just as good or better than the original
shape for the purpose of typical BST operations. Perhaps it is
good for partial credit.
--
"GNU does not eliminate all the world's problems,
only some of them."
--Richard Stallman
.
- 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
- Re: hacker challenge - traverse a list
- From: Ben Pfaff
- Re: hacker challenge - traverse a list
- From: Richard Harter
- hacker challenge - traverse a list
- Prev by Date: Re: hacker challenge - traverse a list
- 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
|