Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Binary search tree traversal that compares two pointers for equality

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#?

like image 327
Valentin V Avatar asked Feb 26 '10 08:02

Valentin V


People also ask

What is preferred traversal for determine if two trees are equal?

Two trees are identical when they have same data and arrangement of data is also same. To identify if two trees are identical, we need to traverse both trees simultaneously, and while traversing we need to compare data and children of the trees. Recommended PracticeDetermine if Two Trees are IdenticalTry It!

How would you check if two binary trees are identical?

Solution Breakdown Two trees 'A' and 'B' are identical if: data on their roots is the same or both roots are null. left sub-tree of 'A' is identical to the left sub-tree of 'B' right sub-tree of 'A' is identical to the right sub-tree of 'B'

Can BST have two same values?

Of course yes. One node in BST has two children which are left child and right child. Left child has smaller value than parent node, meanwhile the right child has larger or equal value of parent node. Here is an example of BST with duplicate value.


1 Answers

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.

like image 62
John Feminella Avatar answered Oct 26 '22 01:10

John Feminella