C# OOP: Binary Search Tree

Add new node to BS tree

To add a new node to the tree, we need a recursive process to locate the appropriate location of the tree. The process starts from the root node. If the tree is empty, the new node will become the root node. If the tree is not empty, the new node will be checked against the parent node. If it is less than the parent node, the process will look for the proper location in the left side, otherwise, it looks in the right side. If the parent node is equal to the new node, it will do nothing. This process continues recursively until it finds the proper location.

Add a new node to the tree  

///C# code to insert a node to the tree
public TreeNode insert(TreeNode Tree, int Tar)
{

//The place to insert the node
if(Tree==null){
TreeNode item= new TreeNode(Tar);
Tree=item;

}

else{

//insert to the left
if(Tar<Tree.data) {Tree.left=insert(Tree.left,Tar);Tree.left.parent=Tree;}

//insert to the right
else if(Tar>Tree.data){Tree.right=insert(Tree.right,Tar);Tree.right.parent=Tree;}

}

return Tree;

}


}



Comments




This website intents to provide free and high quality tutorials, examples, exercises and solutions, questions and answers of programming and scripting languages:
C, C++, C#, Java, VB.NET, Python, VBA,PHP & Mysql, SQL, JSP, ASP.NET,HTML, CSS, JQuery, JavaScript and other applications such as MS Excel, MS Access, and MS Word. However, we don't guarantee all things of the web are accurate. If you find any error, please report it then we will take actions to correct it as soon as possible.