Binary Search Tree

A Binary Search Tree is a binary tree with a search property where elements in the left sub-tree are less than the root and elements in the right sub-tree are greater than the root.

Ex

Binary Search Tree

Walking (Traversing) a Binary Search Tree

There can be 3 types of tree traversals in a binary tree as below.

Pre-Order traversal

In this traversal the traversal happens in the following order.

For the binary search tree, displayed above the Pre-Order traversal would be as follows.

Pre-Order traversal

The C# implementation for the same is as follows.

public void PreOrder_Rec (TNode root)

{

if (root != null)

{

Console.Write(root.Data +" ");

PreOrder_Rec(root.Left);

PreOrder_Rec(root.Right);

}

}

In-Order traversal

In this traversal the traversal happens in following order:

For the binary search tree, displayed above the In-Order traversal would be as follows.

In-Order traversal

The C# implementation for that is as follows.

public void InOrder_Rec(TNode root)

{

if (root != null)

{

InOrder_Rec(root.Left);

Console.Write(root.Data +" ");

InOrder_Rec(root.Right);

}

}

Post-Order traversal

In this traversal the traversal happens in the following order:

For the binary search tree, displayed above the Post-Order traversal would be as follows.

Post-Order traversal

The C# implementation for that is as follows:

public void PostOrder_Rec(TNode root)

{

if (root != null)

{

PostOrder_Rec(root.Left);

PostOrder_Rec(root.Right);

Console.Write(root.Data +" ");

}

}

Important Notes