C# OOP: Binary Search Tree

Search a node in BS tree

Step 5: Searching for a node in the tree

To search for a node in the tree, we need a recursive function find(). This function firstly tests whether the tree is empty. If the tree is not empty, the target value is compared firstly with the data of the root node. If the target value is less than the data of the root node, the search process will continue to left side. It continues to the right side if the target value is greater than the data. The process stops when the data of a node is equal to the target value or when it reaches the end of the tree.

public TreeNode find(TreeNode Tree,int Tar){
if(Tree==null) return null;
if(Tar<Tree.data) //look in the left side
  return find(Tree.left,Tar);
else if(Tar>Tree.data)//look in the right side
  return find(Tree.right,Tar);
else return Tree; //found node


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.