Reputation: 1
Have been searching on web for more than 5 hours and cant find a general BT Preorder visit pseudocode. Thanks in advance. I just find short pseudocodes like this
Algorithm postorder(T, v)
Input: A binary tree T and a node v of T.
Output: Depends on the action performed on a visit to a node.
if T.hasLeft(v)
postorder(T, T.left(v)) // recursively traverse left subtree
if T.hasRight(v)
postorder(T, T.right(v)) // recursively traverse right subtree
visit node v
Upvotes: 0
Views: 512
Reputation: 15310
The difference between preorder, inorder, and postorder is simply the order in which the nodes are visited, relative to the children:
You posted this:
Algorithm postorder(T, v)
Input: A binary tree T and a node v of T.
Output: Depends on the action performed on a visit to a node.
if T.hasLeft(v)
postorder(T, T.left(v)) // recursively traverse left subtree
if T.hasRight(v)
postorder(T, T.right(v)) // recursively traverse right subtree
visit node v
To change among the behaviors, change the order of execution. Here's some generic code:
AnyOrder:
AnyOrder(T, v, order)
if order is 'pre'
visit(v)
AnyOrder(T, T.left(v), order)
if order is 'in'
visit(v)
AnyOrder(T, T.right(v), order)
if order is 'post'
visit(v)
Upvotes: 1