Tuesday, July 31, 2012

Binary Tree and It's Traversal

A tree is called a binary tree where each node has zero, one, or two children ie. at most 2 children.

There are three different methods for traversing binary trees: preorder, postorder and in-order.

Preorder
preorder: Current node, left subtree, right subtree

preorder(node)
visit(node)
if node.left != null then preorder(node.left)
if node.right != null then preorder(node.right)

Postorder
postorder: Left subtree, right subtree, current node

postorder(node)
if node.left != null then postorder(node.left)
if node.right != null then postorder(node.right)
visit(node)

Inorder
in-order: Left subtree, current node, right subtree

inorder(node)
if node.left != null then inorder(node.left)
visit(node)
if node.right != null then inorder(node.right)

Example

If we have a tree as shown above, then the output for different traversal method will be as:
1. preorder : 50, 30, 20, 40, 90, 100
2. postorder : 20, 40, 30, 100, 90, 50
3. inorder : 20, 30, 40, 50, 90, 100

No comments:

Post a Comment