Re: PreOrder Tree Traversal
- From: Mark Space <markspace@xxxxxxxxxxxxxx>
- Date: Wed, 27 Feb 2008 23:08:53 GMT
Jeff Higgins wrote:
public boolean hasNext() {
Here is Michael Abrash's algorithm, adapted to Java. Anywhere I have the "vistNode()" call, you should return "true." Where I return, you should return "false." This is an in-order traversal, it shouldn't be hard to adapt to pre-order.
private void abrashInOrder() {
// Micheal Abrash, Zen of graphics programming.
if (this.tree == null) {
return;
}
Stack<BinaryTreeNode> nodeStack = new Stack<BinaryTreeNode>();
BinaryTreeNode curr = this.tree;
while (true) {
while (curr.left != null) {
nodeStack.push(curr);
curr = curr.left;
}
while (true) {
visitNode(curr);
if (curr.right != null) {
curr = curr.right;
break;
}
if (!nodeStack.isEmpty()) {
curr = nodeStack.pop();
} else {
return;
}
}
}
}
Here is the Morris algorithm. It uses no stack, but does modify the tree as it traverses it. It therefore probably is not well suited to multi-tasking and concurrent use, but it will traverse any tree with no additional memory requirement, making it highly deterministic, and also very pithy on low-memory systems.
private void morrisInOrder() {
// J. M. Morris, "Traversing binary trees simply and cheaply"
// Information Processing Letters, December 1979
if (this.tree == null) {
return;
}
BinaryTreeNode p = tree;
while (p != null) {
if (p.left == null) {
visitNode(p);
p = p.right;
} else {
BinaryTreeNode pre = p.left;
while (pre.right != null && pre.right != p) {
pre = pre.right;
}
if (pre.right == null) {
pre.right = p;
p = p.left;
} else {
pre.right = null;
visitNode(p);
p = p.right;
}
}
}
}
.
- Follow-Ups:
- Re: PreOrder Tree Traversal
- From: Jeff Higgins
- Re: PreOrder Tree Traversal
- References:
- PreOrder Tree Traversal
- From: Jeff Higgins
- Re: PreOrder Tree Traversal
- From: Mark Space
- Re: PreOrder Tree Traversal
- From: Jeff Higgins
- PreOrder Tree Traversal
- Prev by Date: Re: PreOrder Tree Traversal
- Next by Date: Re: PreOrder Tree Traversal
- Previous by thread: Re: PreOrder Tree Traversal
- Next by thread: Re: PreOrder Tree Traversal
- Index(es):
Relevant Pages
|
|