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 *root;
- void buildTree(); // Функция постройки дерева
- void insertFromChild(TreeNode*, int);
- void insertFromRoot(int);
- void destroyTree(TreeNode*);
- void preorderPrint(TreeNode*);
- void findMaxValue(TreeNode*, int&);
- int main() {
- setlocale(LC_ALL, "rus");
- buildTree();
- preorderPrint(root);
- int k = -1e9 - 1;
- if (root != NULL) {
- k = root->data;
- findMaxValue(root, k);
- cout << "\nНаибольшое значение ключа из всех узлов дерева: " << k << '\n';
- } else
- cout << "\nВаше дерево пустое!\n";
- destroyTree(root);
- 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 (root != NULL) {
- insertFromChild(root, key);
- }
- else {
- root = new TreeNode;
- root->data = key;
- root->left = NULL;
- root->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 findMaxValue(TreeNode *root, int &maxValue) {
- if (root == NULL) {
- return;
- }
- maxValue = max(maxValue, root->data);
- findMaxValue(root->left, maxValue);
- findMaxValue(root->right, maxValue);
- }
Add Comment
Please, Sign In to add comment