Exercise 12.1-4

Give recursive algorithms that perform preorder and postorder tree walks in \(\Theta(n)\) time on a tree of \(n\) nodes.

PREORDER-TREE-WALK(x)

1 if x ≠ NIL:

2     print x.key

3     PREORDER-TREE-WALK(x.left)

4     PREORDER-TREE-WALK(x.right)

POSTORDER-TREE-WALK(x)

1 if x ≠ NIL:

2     POSTORDER-TREE-WALK(x.left)

3     POSTORDER-TREE-WALK(x.right)

4     print x.key