Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <climits>
- #include <algorithm>
- using namespace std;
- class Node {
- private:
- int data;
- Node *left;
- Node *right;
- friend class Tree;
- public:
- Node(int value): data(value), left(NULL), right(NULL) {}
- };
- class Tree {
- private:
- Node *root;
- void preOrder(Node *root) {
- if (root == NULL) {
- return ;
- }
- cout << root->data << " ";
- preOrder(root->left);
- preOrder(root->right);
- }
- void inOrder(Node *root) {
- if (root == NULL) {
- return ;
- }
- inOrder(root->left);
- cout << root->data << " ";
- inOrder(root->right);
- }
- void postOrder(Node *root) {
- if (root == NULL) {
- return ;
- }
- postOrder(root->left);
- postOrder(root->right);
- cout << root->data << " ";
- }
- void insert(Node *root, int value) {
- if (value < root->data) {
- if (root->left == NULL) {
- root->left = new Node(value);
- return ;
- }
- insert(root->left, value);
- return ;
- }
- if (root->right == NULL) {
- root->right = new Node(value);
- return ;
- }
- insert(root->right, value);
- }
- int getHeight(Node *root) {
- if (root == NULL) {
- return 0;
- }
- return max(getHeight(root->left), getHeight(root->right)) + 1;
- }
- int getMax(Node *root) {
- if (root->right == NULL) {
- return root->data;
- }
- return getMax(root->right);
- }
- public:
- Tree(): root(NULL) {}
- void preOrder() {
- preOrder(root);
- }
- void inOrder() {
- inOrder(root);
- }
- void postOrder() {
- postOrder(root);
- }
- void insert(int value) {
- if (root == NULL) {
- root = new Node(value);
- return ;
- }
- insert(root, value);
- }
- int getHeight() {
- return getHeight(root);
- }
- int getMax() {
- if (root == NULL) {
- return INT_MIN;
- }
- return getMax(root);
- }
- };
- int main() {
- int arr[10] = {5, 3, 7, 2, 8, 10, 9, 1, 4, 6};
- Tree tree;
- for (int i = 0; i < 10; ++i) {
- tree.insert(arr[i]);
- }
- tree.preOrder();
- cout << endl;
- tree.inOrder();
- cout << endl;
- tree.postOrder();
- cout << endl;
- cout << "Height = " << tree.getHeight() << endl;
- cout << "MAX = " << tree.getMax() << endl;
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement