Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- using namespace std;
- struct TreeNode {
- int data;
- TreeNode *left;
- TreeNode *right;
- };
- TreeNode *root1 = NULL, *root2 = NULL;
- void buildTree(); // Функция постройки дерева
- void initCopyTree();
- void insertFromChild(TreeNode*, int);
- void insertFromRoot(int);
- void destroyTree(TreeNode*);
- void preorderPrint(TreeNode*);
- void copyTree(TreeNode*, TreeNode*);
- int main() {
- setlocale(LC_ALL, "rus");
- buildTree();
- initCopyTree();
- preorderPrint(root2);
- destroyTree(root2);
- destroyTree(root1);
- return 0;
- }
- void insertFromChild(TreeNode *leaf, int key) {
- if (key < leaf->data) {
- if (leaf->left != NULL)
- insertFromChild(leaf->left, key);
- else {
- leaf->left = new TreeNode;
- leaf->left->data = key;
- leaf->left->left = NULL;
- leaf->left->right = NULL;
- }
- }
- else {
- if (leaf->right != NULL)
- insertFromChild(leaf->right, key);
- else {
- leaf->right = new TreeNode;
- leaf->right->data = key;
- leaf->right->left = NULL;
- leaf->right->right = NULL;
- }
- }
- }
- void insertFromRoot(int key) {
- if (root1 != NULL) {
- insertFromChild(root1, key);
- }
- else {
- root1 = new TreeNode;
- root1->data = key;
- root1->left = NULL;
- root1->right = NULL;
- }
- }
- void buildTree() {
- int n;
- cout << "Enter count of elements to insert in bintree:\n";
- cin >> n;
- cout << "Input elements:\n";
- for (int i = 0; i < n; i++) {
- int req;
- cin >> req;
- insertFromRoot(req);
- }
- }
- void destroyTree(TreeNode *leaf) {
- if (leaf != NULL) {
- destroyTree(leaf->left);
- destroyTree(leaf->right);
- delete leaf;
- }
- }
- void preorderPrint(TreeNode *root) {
- if (root == NULL) {
- return;
- }
- cout << root->data << ' ';
- preorderPrint(root->left);
- preorderPrint(root->right);
- }
- void initCopyTree() {
- if (root1 != NULL && root2 == NULL) {
- root2 = new TreeNode;
- root2->data = root1->data;
- root2->left = NULL;
- root2->right = NULL;
- copyTree(root1, root2);
- }
- }
- void copyTree(TreeNode *rootFrom, TreeNode *rootTo) {
- if (rootFrom->left != NULL) {
- rootTo->left = new TreeNode;
- rootTo->left->data = rootFrom->left->data;
- rootTo->left->left = NULL;
- rootTo->left->right = NULL;
- copyTree(rootFrom->left, rootTo->left);
- }
- else {
- rootTo->left = NULL;
- }
- if (rootFrom->right != NULL) {
- rootTo->right = new TreeNode;
- rootTo->right->data = rootFrom->right->data;
- rootTo->right->left = NULL;
- rootTo->right->right = NULL;
- copyTree(rootFrom->right, rootTo->right);
- }
- else {
- rootTo->right = NULL;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement