Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <fstream>
- using namespace std;
- typedef struct Node
- {
- int data;
- struct Node* pLeft;
- struct Node* pRight;
- }NODE;
- typedef NODE* TREE;
- void Init(TREE& t)
- {
- t = NULL;
- }
- bool is_Empty(TREE t)
- {
- if (t == NULL)
- return true;
- return false;
- }
- NODE* GetNode(int value)
- {
- NODE* p = new NODE;
- if (p == NULL)
- return NULL;
- p->data = value;
- p->pLeft = p->pRight = NULL;
- return p;
- }
- void InsertNode(TREE& t, NODE *p)
- {
- if (t == NULL)
- {
- t = p;
- }
- else
- {
- if (t->data > p->data)
- {
- InsertNode(t->pLeft, p);
- }
- else
- {
- InsertNode(t->pRight, p);
- }
- }
- }
- NODE* SearchNode(TREE t, int value)
- {
- if (t == NULL)
- {
- return NULL;
- }
- if (t->data == value)
- return t;
- else
- {
- if (t->data > value)
- return SearchNode(t->pLeft, value);
- else
- {
- return SearchNode(t->pRight, value);
- }
- }
- }
- void ReplaceNode(TREE &p , TREE &q)
- {
- if (p->pLeft == NULL)
- {
- ReplaceNode(p, q->pLeft);
- }
- else
- {
- p->data = q->data;
- p = q;
- q = q->pRight;
- }
- }
- void DeleteNode(TREE& t, int value)
- {
- if (t == NULL)
- return;
- if (t->data > value)
- DeleteNode(t->pLeft, value);
- if (t->data < value)
- DeleteNode(t->pRight, value);
- else
- {
- NODE* p = t;
- if (t->pLeft == NULL)
- t = t->pRight;
- else
- {
- if (t->pRight == NULL)
- t = t->pLeft;
- else
- {
- NODE* q = t->pRight;
- ReplaceNode(p, q);
- }
- }
- }
- }
- void Input(const char* fileinp, TREE& t)
- {
- ifstream inp;
- inp.open(fileinp);
- if (!inp.is_open())
- {
- cout << "ERROR: Can not open the file to read data.";
- }
- else
- {
- int x;
- while (inp >> x)
- {
- InsertNode(t, GetNode(x));
- }
- }
- }
- void LNR_to_array(TREE t, int a[], int &i)
- {
- if (t != NULL)
- {
- LNR_to_array(t->pLeft, a, i);
- a[i] = t->data;
- i++;
- LNR_to_array(t->pRight, a, i);
- }
- }
- void Output(const char* fileout, TREE t)
- {
- ofstream out;
- out.open(fileout);
- if (!out.is_open())
- {
- cout << "ERROR: Can not open the file to write data.";
- }
- else
- {
- int a[100];
- int i = 0;
- LNR_to_array(t, a, i);
- for (int j = 0; j < i; j++)
- {
- if (j != i - 1)
- out << a[j] << " ";
- else
- {
- out << a[j];
- }
- }
- }
- }
- int main()
- {
- TREE t;
- Init(t);
- Input("data.txt", t);
- Output("output.txt", t);
- cout << SearchNode(t, 86)->data;
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement