views:

107

answers:

2

I'm reading the Cormen algorithms book (binary search tree chapter) and it says that there are two ways to traverse the tree without recursion:

using stack and a more complicated but elegant solution that uses no stack but assumes that two pointers can be tested for equality

I've implemented the first option (using stack), but don't know how to implement the latter. This is not a homework, just reading to educate myself.

Any clues as to how to implement the second one in C#?

A: 

Assuming that the nodes in the tree are references and the values are references, you can always call the static ReferenceEquals method on the Object class to compare to see if the references for any two nodes/values are the same.

casperOne
This part I know, what I don't know is the rest, the 'traversal' part
Valentin Vasiliev
+3  A: 

Sure thing. You didn't say what kind of traversal you wanted, but here's the pseudocode for an in-order traversal.

t = tree.Root;
while (true) {
  while (t.Left != t.Right) {
    while (t.Left != null) {   // Block one.
      t = t.Left;
      Visit(t);
    }
    if (t.Right != null) {     // Block two.
      t = t.Right;
      Visit(t);
    }
  }

  while (t != tree.Root && (t.Parent.Right == t || t.Parent.Right == null)) {
    t = t.Parent;
  }
  if (t != tree.Root) {        // Block three.
    t = t.Parent.Right;
    Visit(t);
  } else {
    break;
  }
}

To get pre- or post-order, you rearrange the order of the blocks.

John Feminella
you start of with a while(true), yet I see no break nowhere?
Toad
@reinier: Whoops! Good catch. You need to break if you're not at the root in the last step. Fixed.
John Feminella
@john: still impressed with the algorithm. Especially if you did this of the top of your head. +1
Toad
Well, someone should probably test this to make sure it's right. ;)
John Feminella