tree *toBinaryTree(int pre[], int in[], int start, int end) { static int index = 0; if(start > end) { return NULL; } tree *newnode = (tree *)malloc(sizeof(tree)); newnode->key = pre[index]; newnode->left = NULL; newnode->right = NULL; index++; if(start == end) { return newnode; } int i, pos; for(i = start; i <= end; i++) { if(in[i] == newnode->key) { pos = i; } } newnode->left = toBinaryTree(pre, in, start, pos - 1); newnode->right = toBinaryTree(pre, in, pos + 1, end); return newnode; }
cnode *toBinaryTree(cnode *head, cnode *tail) { cnode *root; cnode *slow = head; cnode *fast = head; while (head != tail && fast != tail -> next && fast -> next != tail -> next) { slow = slow -> next; fast = fast -> next -> next; } root = slow; if (head -> info > tail -> info) return NULL; if (root -> previous != NULL) root -> previous = toBinaryTree(head, root -> previous); if (root -> next != NULL) root -> next = toBinaryTree(root -> next, tail); return(root); }
int main() { int n, i; scanf("%d", &n); if(n <= 0) { printf("INVALID INPUT\n"); return 0; } int pre[n], in[n]; for(i = 0; i < n; i++) { scanf("%d", &pre[i]); if(pre[i] >= 2147483648 || pre[i] <= -2147483648) { printf("INVALID INPUT\n"); return 0; } } scanf("%d", &in[0]); int max = in[0]; for(i = 1; i < n; i++) { scanf("%d", &in[i]); if(in[i] < in[i - 1]) { printf("INVALID INORDER TRAVERSAL\n"); return 0; } } tree *root = toBinaryTree(pre, in, 0, n - 1); preorder(root); return 0; }
int main() { printf("Enter numbers for doubly linked list in sorted order\n"); int holding = 0; char junk = '.'; junk = getchar(); if (atoi(&junk) == 0 && junk != '0') { printf("Null list added, binary tree is null.\n"); exit(1); } int x = 1; char *build = malloc(sizeof(char) * x); char *tmp = '\0'; build[0] = '\0'; while (atoi(&junk) != 0 || junk == '0') { build[x-1] = junk; junk = getchar(); x++; tmp = realloc(build, sizeof(char) * x); if (tmp != NULL) build = tmp; else { printf("Out of memory, program exit."); free(build); exit(3); } build[x-1] = '\0'; } holding = atoi(build); free(build); cnode *head = malloc(sizeof(cnode)); head -> info = holding; head -> previous = NULL; head -> next = NULL; cnode *tail = head; while (junk == ' ') { scanf("%d", &holding); if (holding < tail -> info) { printf("List is out of order, program exit.\n"); freeDoublyLinkedList(head, tail); exit(2); } tail = insertTail(head, tail, holding); junk = getchar(); } printf("Doubly Linked List Contents:\n"); cnode *ptr = head; while (ptr != NULL) { printf("%d ", ptr -> info); ptr = ptr -> next; } printf("\n"); cnode *root = toBinaryTree(head, tail); printf("Binary Search Tree Contents:\n"); printBinaryTree(root); printf("\n"); freeBinaryTree(root); return 0; }