Re: Tomazos Binary Tree Traverse Algorithm
- From: andrew@xxxxxxxxxxx
- Date: Mon, 10 Nov 2008 23:55:31 -0800 (PST)
On Nov 10, 10:09 pm, "Paul E. Black" <p.bl...@xxxxxxx> wrote:
On Monday 10 November 2008 05:37, and...@xxxxxxxxxxx wrote:
Tomazos Binary Tree Traverse Algorithm
Andrew Tomazos <and...@xxxxxxxxxxx> <http://www.tomazos.com>
2008-11-10
Abstract
We describe an algorithm that traverses a binary tree in O(n) time and
O(1) space. Each node is visited exactly three times, once preorder,
once inorder and once postorder. We provide a conceptual description,
an implementation in C and the sketch of a proof.
It is possible to simulate this journey only keeping local
information:
1. The current castle
2. Which of the three important sides (WEST, SOUTH, EAST) we are on of
the current castle.
while (p != NULL) {
if (state == west) {
visit_preorder(p);
if (p->left_child)
p = p->left_child;
else
state = south;
}
if (state == south) {
visit_inorder(p);
if (p->right_child) {
p = p->right_child;
state = west;
}
else
state = east;
}
if (state == east) {
visit_postorder(p);
if (p->parent) {
if (p == p->parent->left_child)
state = south;
else // p == p->parent->right_child
state = east;
}
p = p->parent;
}
}
Andrew,
Your algorithm works nicely.
I consider it confusing to say that the algorithm take Theta(1)
space. Your binary tree data structure requires every node to have a
pointer to its parent, which is not typical. I suggest characterizing
the algorithm as needing Theta(n) space or calling it something like
Traversal Algorithm for Binary Trees with Parent Pointers.
One can write an algorithm to do the same traversal in a binary tree
without parent pointers and really use constant space. The trick is
to reverse pointers on the way down, so you can find your parent, then
reverse them again on the way up to restore them to their initial
state.
Yes, a number of people have mentioned that it requires an O(1)
Parent[N] function to work. I know a subset of trees have this
facility (redblack trees, btrees, heaps, trees stored in arrays (ie
parent(i) = i/2)).
Thats a cool idea about reusing the child pointers to temporarily be
parent pointers, I hadn't thought of that. You would have to turn
off read access while iterating it, and make sure you aren't
interrupted half way through and leave the tree in a corrupted state.
-Andrew.
.
- Follow-Ups:
- Re: Tomazos Binary Tree Traverse Algorithm
- From: Ben Pfaff
- Re: Tomazos Binary Tree Traverse Algorithm
- References:
- Tomazos Binary Tree Traverse Algorithm
- From: andrew
- Re: Tomazos Binary Tree Traverse Algorithm
- From: Paul E. Black
- Tomazos Binary Tree Traverse Algorithm
- Prev by Date: Re: bicomp, a bidirectional computer, released.
- Next by Date: Re: bicomp, a bidirectional computer, released.
- Previous by thread: Re: Tomazos Binary Tree Traverse Algorithm
- Next by thread: Re: Tomazos Binary Tree Traverse Algorithm
- Index(es):
Relevant Pages
|
Loading