Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- //по входной последовательности построить дерево бинарного поиска и
- //9.найти длину пути из узла а в узел б; если такого пути не существует, то вывести сообщение об этом;
- #include <iostream>
- #include <fstream>
- using namespace std;
- ifstream in("input.txt");
- //ofstream out("output.txt");
- #define out cout
- struct tree {
- int inf;//информация узла
- tree *left, *right;//указатели на левого и правого потомка
- };
- tree *root;
- void add (int x, tree *&root) { //функция добавления элемента в дерево бинарного поиска
- if (!root) { //если узел пуст
- root= new tree;
- root->inf = x;
- root->left = root->right = NULL;
- } else if (x < root->inf) // если узел не пуст
- add(x, root->left);
- else add(x, root->right);
- }
- void deleteTree (tree *&root) { //функция удаления дерева
- if (root) {
- deleteTree(root->left);
- deleteTree(root->right);
- delete(root);
- root=NULL;
- }
- }
- void PrintList (tree *root, int lvl) { //функция для печати листьев
- for (int i = 0; i < lvl; i++) cout << "| ";
- if (root) {
- cout << root->inf << endl;
- PrintList(root->right, lvl + 1);
- PrintList(root->left, lvl + 1);
- // cout << endl;
- /*if ((root->left==NULL) && (root->right==NULL)) out<<root->inf<<" ";
- else {
- PrintList(root->left, i + 1);
- PrintList(root->right, i + 1);
- }*/
- } else cout << "*\n";
- }
- int findPath(tree* root, tree* target) {
- tree* node = root;
- int path = 0;
- while (node) {
- if (node->inf < target->inf)
- path++;
- }
- }
- /*
- 1
- 2
- 4
- 4
- 3
- 5
- 6
- */
- void preorder (tree *root) { //прямой обход
- if (root) {
- out<<root->inf<<" ";
- preorder(root->left);
- preorder(root->right);
- }
- }
- int main() {
- int x;
- while(in.peek() != EOF) {
- in >> x;
- add(x, root);
- PrintList(root, 0);
- cout << "=====================================\n";
- }
- //PrintList(root, 0);
- deleteTree(root);
- in.close();
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement