Binary Tree Insert and Search operations

Manojjupally
Posted by Manojjupally under C# category on | Points: 40 | Views : 1008
Binary Tree class to hold left tree, Right tree and data node

class BinTree
{
public BinTree left;
public BinTree right;
public int data;
}


Insert Into Binary Tree

  static BinTree root;
public static void InSertNode(int x)
{
BinTree temp;
BinTree temp1;
BinTree curNode = new BinTree();
curNode.data = x;
if (root == null)
{
root = curNode;
}
else
{
temp1 = temp = root;

while (temp1 != null)
{
if (curNode.data > temp.data && temp.right != null)
{
temp = temp.right;
}
else if (curNode.data < temp.data && temp.left != null)
{
temp = temp.left;
}
else
temp1 = null;
}

if (curNode.data > temp.data)
temp.right = curNode;
else
temp.left = curNode;
}
}


PreOrder Traversal

 public static void PreOrder(BinTree root)
{
if (root!= null)
{
Console.WriteLine(root.data);
PreOrder(root.left);
PreOrder(root.right);
}
}


InOrder Traversal

 public static void InOrder(BinTree root)
{
if (root!= null)
{
PreOrder(root.left);
Console.WriteLine(root.data);
PreOrder(root.right);
}
}


PostOrder Traversal

 public static void InOrder(BinTree root)
{
if (root!= null)
{
PreOrder(root.left);
PreOrder(root.right);
Console.WriteLine(root.data);
}
}

Comments or Responses

Login to post response