C++ tutorial: structure-Search a node in the tree


C++ Structure: Building a Binary Search Tree

Step 5: Search 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.

ListElem *find(ListElem *T, int Tar){
  if(T==NULL) return NULL;
  if(Tar<T->data) //look in the left side
    return find(T->pLeft,Tar);
  else if(Tar>T->data)//look in the right side
    return find(T->pRight,Tar);
  else return T; //found node
}




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.