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#?
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!
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'
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With