Программы не добавляют более одного узла в дерево.При поиске появляется только одна информация об узле - PullRequest
0 голосов
/ 10 декабря 2018
#include<iostream>
#include <conio.h>

using namespace std;


class Student_Node{
public:
    Student_Node *right,*left;
    int ID;
    string First_Name;
    int Age;
    float Test_Score,CGPA;

};

class Student_Tree{
Student_Node *root;

public:
    Student_Tree()
    {
        root=NULL;
    }
    void take_input();
    void build_tree(int id,string name,int age,float score,float cgpa);
    void BST_search();
    void input_sort(Student_Node *n, Student_Node *r);
    void Search (int id);
    void searching(int id,Student_Node *r);
    void Node_Depth(int id);
    void FindHeight();
    int Height(Student_Node* root);
};

/////////////////////////////////////////////////////////////////////////

Это моя функция сборки.В take_input() я применяю цикл, чтобы дать пользователю возможность добавлять столько узлов, сколько он хочет.В цикле пользователь дает данные, которые передаются obj.build_tree(int id,string name,int age,float score,float cgpa);, но он добавляет только один узел и больше ничего.Когда я вызываю мой Search (int id), он выводит только данные первого узла.

 void Student_Tree::build_tree(int id,string name,int age,float score,float 
  cgpa)
  {
  Student_Node *n= new Student_Node(); 
    n->ID=id;
  n->First_Name=name;
 n->Age=age;
 n->CGPA=cgpa;
 n->Test_Score=score;
 if(root==NULL)
 {
    root=n;
 }
 else
 {
    input_sort(n,root);
 }
 }

void Student_Tree::input_sort(Student_Node *n, Student_Node *r)
{
if(r->ID>=n->ID)
{
    if(r->left!=NULL)
    {
        input_sort(n,r->left);
    }
    else
    {
        n=r->left;
    }
}

if(r->ID<=n->ID)
{
    if(r->right!=NULL)
    {
        input_sort(n,r->right);
    }
    else
    {
        n=r->right;
    }
    }
}



/////// inout takes input from user, then sends it to the build fucntion
/////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////
void Student_Tree::Search (int id)
{
Student_Node *n=new Student_Node();
n=root;
if(n==NULL)
{
    cout<<"Tree is empty"<<endl;
}
else 
{
    searching(id,root);
}
}
void Student_Tree::searching(int id,Student_Node *r)
{
if(r->ID>=id)
{
    if(r->ID==id)
    {
        cout<<"ID"<<" "<<"Age"<<" "<<"CGPA"<<" "<<"First Name"<<" "<<"Test 
Score"<<endl;
        cout<<"------------------------------------------------------------- 
---------"<<endl;
        cout<<r->ID<<" "<<r->Age<<" "<<r->CGPA<<" "<<r->First_Name<<" "<<r-> 
Test_Score;
    }
    else
    {
        searching(id,r->left);
    }
}
else if(r->ID<=id)
{
    if(r->ID==id)
    {
        cout<<r->ID;
    }
    else
    {
        searching(id,r->right);
    }
}
else
{
    cout<<"Roll No Not found"<<endl;
   } 
}

void Student_Tree::FindHeight()
{
Height(root);
}

 int Student_Tree::Height(Student_Node *r)
{  
if(r==NULL)
{
    return 0;
}

else
{
    int lb=Height(r->left);
    int rb=Height(r->right);
    cout<<max(lb,rb)+1;
    return max(lb,rb)+1;
}
}
/////////////////////////////////////////////////////////////////////////
void Student_Tree::Node_Depth(int id) 
{
int depth = 0;
Student_Node *temp = new Student_Node;
temp = root;
// Run the loop untill temp points to a NULL pointer.
while(temp != NULL)
{
    depth++;
    if(temp->ID == id)
    {
        cout<<"\nData found at depth: "<<depth<<endl;
        return;
    }
    // Shift pointer to left child.
    else if(temp->ID > id)
        temp = temp->left;
    // Shift pointer to right child.
    else
        temp = temp->right;
}

cout<<"\n Data not found";
return;
}



void take_input()
{
Student_Tree obj;   
    int ID;
    string First_Name;
    int Age;
    float Test_Score,CGPA;
    cout<<"How many students data do you want to enter?"<<endl;
    int no; cin>>no;
    for(int i=0;i<no;i++)
    {
    cout<<"\t\t\t\tEnter Student Id"<<endl;
    cout<<"\t\t\t\t";cin>>ID;
    cout<<"\t\t\t\tEnter Student First Name"<<endl;
    cout<<"\t\t\t\t";cin>>First_Name;
    cout<<"\t\t\t\tEnter Student Age"<<endl;
    cout<<"\t\t\t\t";cin>>Age;
    cout<<"\t\t\t\tTest Student Score"<<endl;
    cout<<"\t\t\t\t";cin>>Test_Score;
    cout<<"\t\t\t\tEnter Student CGPA"<<endl;
    cout<<"\t\t\t\t";cin>>CGPA;     
    obj.build_tree(ID,First_Name,Age,Test_Score,CGPA);
    }
}
int main()
{
Student_Tree obj;
take_input();
cout<<"Enter node"<<endl;
int n; cin>>n;
obj.Node_Depth(n);
obj.FindHeight();
cout<<"\nEnter id to search"<<endl; int id; cin>>id;
obj.Search(id);

return 0;
}

1 Ответ

0 голосов
/ 10 декабря 2018

Ваша build_tree функция вызывает input_sort, чтобы добавить дополнительный узел.Но input_sort никогда ничего не добавляет к чему-либо еще.Как вы думаете, какой код присоединяет второй узел к дереву?Кажется, что их нет.

 if(root==NULL)
 {
    root=n;
 }
 else
 {
    input_sort(n,root);
 }

Первая часть этого кода добавляет n к дереву, если дерево пусто.Ожидается, что вторая часть добавит n к трем, если дерево не пустое.

void Student_Tree::input_sort(Student_Node *n, Student_Node *r)
{
    if(r->ID>=n->ID)
    {
        if(r->left!=NULL)
        {
            input_sort(n,r->left);
        }
        else
        {
            n=r->left;

Мы уже здесь.Эта функция была вызвана с n как новым добавляемым узлом, и никакой другой указатель на этот узел нигде не был сохранен.Если мы изменим здесь значение n, мы потеряем единственный указатель, который у нас был, на узел, который мы должны были добавить.

Даже если мы не попадаем сюда, в input_sort нет кодагде угодно, чтобы фактически добавить узел в дерево, и build_tree ожидает его.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...