Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- #include <stdlib.h>
- #include <limits.h>
- inline int maxInt(int a, int b) {
- return a > b ? a : b;
- }
- typedef struct Node {
- int data;
- struct Node *left;
- struct Node *right;
- } Node;
- Node* newNode(int value) {
- Node *node = (Node*) malloc(sizeof(Node));
- node->data = value;
- node->left = NULL;
- node->right = NULL;
- return node;
- }
- typedef struct {
- Node *root;
- } Tree;
- Tree* newTree() {
- Tree *tree = (Tree*) malloc(sizeof(Tree));
- tree->root = NULL;
- return tree;
- }
- void nodePreOrder(Node *root) {
- if (root == NULL) {
- return ;
- }
- printf("%d ", root->data);
- nodePreOrder(root->left);
- nodePreOrder(root->right);
- }
- void treePreOrder(Tree *tree) {
- if (tree == NULL) {
- return ;
- }
- nodePreOrder(tree->root);
- }
- void nodeInOrder(Node *root) {
- if (root == NULL) {
- return ;
- }
- nodeInOrder(root->left);
- printf("%d ", root->data);
- nodeInOrder(root->right);
- }
- void treeInOrder(Tree *tree) {
- if (tree == NULL) {
- return ;
- }
- nodeInOrder(tree->root);
- }
- void nodePostOrder(Node *root) {
- if (root == NULL) {
- return ;
- }
- nodePostOrder(root->left);
- nodePostOrder(root->right);
- printf("%d ", root->data);
- }
- void treePostOrder(Tree *tree) {
- if (tree == NULL) {
- return ;
- }
- nodePostOrder(tree->root);
- }
- void nodeInsert(Node *root, int value) {
- if (value < root->data) {
- if (root->left == NULL) {
- root->left = newNode(value);
- return ;
- }
- nodeInsert(root->left, value);
- return ;
- }
- if (root->right == NULL) {
- root->right = newNode(value);
- return ;
- }
- nodeInsert(root->right, value);
- }
- void treeInsert(Tree *tree, int value) {
- if (tree->root == NULL) {
- tree->root = newNode(value);
- return ;
- }
- nodeInsert(tree->root, value);
- }
- void treeBuild(Tree *tree, int *values, int n) {
- int i;
- for (i = 0; i < n; ++i) {
- treeInsert(tree, values[i]);
- }
- }
- int nodeGetHeight(Node *root) {
- if (root == NULL) {
- return 0;
- }
- return maxInt(nodeGetHeight(root->left), nodeGetHeight(root->right)) + 1;
- }
- int treeGetHeight(Tree *tree) {
- if (tree == NULL) {
- return 0;
- }
- return nodeGetHeight(tree->root);
- }
- int nodeMaximum(Node *root) {
- if (root == NULL) {
- return INT_MIN;
- }
- if (root->right == NULL) {
- return root->data;
- }
- return nodeMaximum(root->right);
- }
- int treeMaximum(Tree *tree) {
- if (tree == NULL) {
- return INT_MIN;
- }
- return nodeMaximum(tree->root);
- }
- int main() {
- int arr[10] = {5, 3, 7, 2, 8, 10, 9, 1, 4, 6};
- Tree *tree = newTree();
- treeBuild(tree, arr, 10);
- treePreOrder(tree);
- printf("\n");
- treeInOrder(tree);
- printf("\n");
- treePostOrder(tree);
- printf("\n");
- printf("Height = %d\n", treeGetHeight(tree));
- printf("MAX = %d\n", treeMaximum(tree));
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement