Binary search tree traversal that compares two pointers for equality

后端 未结 2 1090
深忆病人
深忆病人 2021-02-09 22:10

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 sta

2条回答
  •  粉色の甜心
    2021-02-09 23:16

    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.

提交回复
热议问题