0% found this document useful (0 votes)
8 views

Trees Code HELP

Uploaded by

Dharnesh Balq
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views

Trees Code HELP

Uploaded by

Dharnesh Balq
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 4

Trees Code HELP

Preorder-Inorder BST
[ //Function to build a binary tree from preorder and inorder
#include <stdio.h> traversals
#include <stdlib.h> struct TreeNode* buildTree(int* preorder, int preorderSize, int*
inorder, int inorderSize){
TreeNode Structure return buildTreeHelper(preorder, 0, preorderSize - 1, inorder,
struct TreeNode { 0, inorderSize-1);
int val; }
struct TreeNode* left;
struct TreeNode* right; //Function to print the inorder traversal of a TreeNode
}; void printInorder(struct TreeNode* root){
if(!root){
//Function to create a new TreeNode return;
struct TreeNode* newTreeNode(int x){ }
struct TreeNode* node = (struct printInorder(root->left);
TreeNode*)malloc(sizeof(struct TreeNode)); printf("%d ",root->val);
node->val = x; printInorder(root->right);
node->left = NULL; }
node->right = NULL;
return node; //Function to print the given array
} void printArray(int* arr, int size){
for(int i = 0; i < size; i++){
//Function to find the index of a value in an array printf("%d ",arr[i]);
int findIndex(int * arr, int start, int end, int value){ }
for(int i = start; i <= end; i++){ printf("\n");
if(arr[i]==value){ }
return i;
} int main(){
} int inorder[] = {9,3,15,20,7};
int preorder[] = {3, 9, 20, 15, 7};
return -1;
} int inorderSize = sizeof(inorder) / sizeof(inorder[0]);
int preorderSize = sizeof(preorder) / sizeof(preorder[0]);

//Recursive helper function to build the tree printf("Inorder Array: ");


struct TreeNode* buildTreeHelper(int* preorder, int preStart, printArray(inorder, inorderSize);
int preEnd, int* inorder, int inStart, int inEnd){
//Base case: If the start indices exceed the end indices, return printf("Preorder Array: ");
NULL printArray(preorder, preorderSize);
if(preStart > preEnd || inStart > inEnd){
return NULL; struct TreeNode* root = buildTree(preorder, preorderSize,
} inorder, inorderSize);

//Create a new TreeNode with value at the current preorder printf("Inorder of Unique Binary Tree Created: \n");
index printInorder(root);
struct TreeNode* root = newTreeNode(preorder[preStart]); printf("\n");
return 0;
//Find the index of the current root value in the inorder }
traversal ]
int inRoot = findIndex(inorder , inStart, inEnd, root->val);

//Calculate the number of elements in the left subtree


int numsLeft = inRoot - inStart;

//Recursively build the left subtree


root->left = buildTreeHelper(preorder, preStart + 1, preStart +
numsLeft, inorder, inStart, inRoot - 1);

//Recursively build the right subtree


root->right = buildTreeHelper(preorder, preStart + numsLeft +
1, preEnd, inorder, inRoot+1, inEnd);

//Return the current root node


return root;
}
Serialize - Deserialize
#include <stdio.h> q->rear = NULL;
#include <stdlib.h> struct TreeNode* node = temp- while (!isQueueEmpty(q)) {
#include <string.h> >data; struct TreeNode* node =
free(temp); dequeue(q);
// Definition for a binary tree node. return node;
struct TreeNode { } token = getToken(&str, ",");
int val; if (token && strcmp(token, "#") !=
struct TreeNode* left; // Check if the queue is empty 0) {
struct TreeNode* right; int isQueueEmpty(struct Queue* q) { struct TreeNode* leftNode =
}; return q->front == NULL; newTreeNode(atoi(token));
} node->left = leftNode;
// Queue node structure for level- enqueue(q, leftNode);
order traversal // Encodes the tree into a single string }
struct QueueNode { char* serialize(struct TreeNode* root)
struct TreeNode* data; { token = getToken(&str, ",");
struct QueueNode* next; if (!root) if (token && strcmp(token, "#") !=
}; return ""; 0) {
struct TreeNode* rightNode =
// Queue structure char* result = (char*)malloc(1024 * newTreeNode(atoi(token));
struct Queue { sizeof(char)); node->right = rightNode;
struct QueueNode* front; strcpy(result, ""); enqueue(q, rightNode);
struct QueueNode* rear; }
}; struct Queue* q = createQueue(); }
enqueue(q, root);
// Function to create a new tree node return root;
struct TreeNode* newTreeNode(int while (!isQueueEmpty(q)) { }
val) { struct TreeNode* curNode =
struct TreeNode* node = (struct dequeue(q); // Inorder traversal
TreeNode*)malloc(sizeof(struct void inorder(struct TreeNode* root) {
TreeNode)); if (curNode == NULL) { if (!root)
node->val = val; strcat(result, "#,"); return;
node->left = NULL; } else { inorder(root->left);
node->right = NULL; char buffer[10]; printf("%d ", root->val);
return node; sprintf(buffer, "%d,", curNode- inorder(root->right);
} >val); }
strcat(result, buffer);
// Function to create a new queue enqueue(q, curNode->left); int main() {
struct Queue* createQueue() { enqueue(q, curNode->right); struct TreeNode* root =
struct Queue* q = (struct } newTreeNode(1);
Queue*)malloc(sizeof(struct Queue)); } root->left = newTreeNode(2);
q->front = q->rear = NULL; root->right = newTreeNode(3);
return q; return result; root->right->left = newTreeNode(4);
} } root->right->right =
newTreeNode(5);
// Function to enqueue a tree node // Helper function to extract tokens
void enqueue(struct Queue* q, struct from a string printf("Original Tree: ");
TreeNode* node) { char* getToken(char** str, const char* inorder(root);
struct QueueNode* temp = (struct delim) { printf("\n");
QueueNode*)malloc(sizeof(struct char* token = strtok(*str, delim);
QueueNode)); *str = NULL; char* serialized = serialize(root);
temp->data = node; return token; printf("Serialized: %s\n", serialized);
temp->next = NULL; }
if (q->rear == NULL) { struct TreeNode* deserialized =
q->front = q->rear = temp; // Decode the encoded data to a tree deserialize(serialized);
return; struct TreeNode* deserialize(char* printf("Tree after deserialization: ");
} data) { inorder(deserialized);
q->rear->next = temp; if (strlen(data) == 0) printf("\n");
q->rear = temp; return NULL;
} free(serialized); // Free the
char* token; allocated memory for the serialized
// Function to dequeue a tree node char* str = data; string
struct TreeNode* dequeue(struct token = getToken(&str, ",");
Queue* q) { return 0;
if (q->front == NULL) struct TreeNode* root = }
return NULL; newTreeNode(atoi(token));
struct QueueNode* temp = q->front;
q->front = q->front->next; struct Queue* q = createQueue();
if (q->front == NULL) enqueue(q, root);
Search in a BST }
#include <stdio.h>
#include <stdlib.h> int main() {
// Creating a BST
// Definition of TreeNode structure for a binary tree node struct TreeNode* root = newTreeNode(5);
struct TreeNode { root->left = newTreeNode(3);
// Value of the node root->right = newTreeNode(8);
int val; root->left->left = newTreeNode(2);
root->left->right = newTreeNode(4);
// Pointer to the left child node root->right->left = newTreeNode(6);
struct TreeNode* left; root->right->right = newTreeNode(10);

// Pointer to the right child node printf("Binary Search Tree:\n");


struct TreeNode* right; printInOrder(root);
printf("\n");
// Constructor to initialize the node with a value
// and set left and right pointers to NULL // Initializing the Solution struct
}; struct Solution solution;
solution.searchBST = searchBST;
// Function to create a new tree node
struct TreeNode* newTreeNode(int val) { // Searching for a value in the BST
struct TreeNode* node = (struct int target = 6;
TreeNode*)malloc(sizeof(struct TreeNode)); struct TreeNode* result = solution.searchBST(root, target);
node->val = val;
node->left = NULL; // Displaying the search result
node->right = NULL; if (result != NULL) {
return node; printf("Value %d found in the BST!\n", target);
} } else {
printf("Value %d not found in the BST.\n", target);
struct Solution { }
// This function searches for a node with a specified value
// in a Binary Search Tree (BST). return 0;
struct TreeNode* (*searchBST)(struct TreeNode* root, int }
val);
}; Delete a node

// Function to search for a node in a Binary Search Tree (BST) #include <stdio.h>
struct TreeNode* searchBST(struct TreeNode* root, int val) { #include <stdlib.h>
// Loop until either the tree is exhausted (NULL)
// or the value is found. // Definition of TreeNode structure for a binary tree node
while (root != NULL && root->val != val) { struct TreeNode {
// Check if the target value is less than the current node's int val;
value. struct TreeNode* left;
// If so, move to the left subtree (values smaller than the struct TreeNode* right;
current node). };
// Otherwise, move to the right subtree (values larger than
the current node). // Function to create a new tree node
root = val < root->val ? root->left : root->right; struct TreeNode* newTreeNode(int val) {
} struct TreeNode* node = (struct
// Return the node containing the target value, if found; TreeNode*)malloc(sizeof(struct TreeNode));
otherwise, return NULL. node->val = val;
return root; node->left = NULL;
} node->right = NULL;
return node;
// Function to perform an in-order traversal of a binary tree and }
print its nodes
void printInOrder(struct TreeNode* root) { // Function to delete a node with a given key from the BST
// Check if the current node is NULL (base case for recursion) struct TreeNode* deleteNode(struct TreeNode* root, int key) {
if (root == NULL) { if (!root) return NULL;
// If NULL, return and terminate the function
return; // If the key is greater than the current node's value, go to the
} right subtree
if (root->val < key) {
// Recursively call printInOrder for the left subtree root->right = deleteNode(root->right, key);
printInOrder(root->left); }
// If the key is smaller than the current node's value, go to
// Print the value of the current node the left subtree
printf("%d ", root->val); else if (root->val > key) {
root->left = deleteNode(root->left, key);
// Recursively call printInOrder for the right subtree }
printInOrder(root->right); // If the current node is the node to be deleted
else { BST FROM PREORDER
// Case 1: The node has no children (leaf node)
if (!root->right && !root->left) { #include <stdio.h>
free(root); #include <stdlib.h>
return NULL; #include <limits.h>
}
// Case 2: The node has only a left child // Definition of the TreeNode structure for a binary tree node
else if (!root->right) { struct TreeNode {
struct TreeNode* temp = root->left; int val;
free(root); struct TreeNode* left;
return temp; struct TreeNode* right;
} };
// Case 3: The node has only a right child
else if (!root->left) { // Function to create a new tree node
struct TreeNode* temp = root->right; struct TreeNode* newTreeNode(int val) {
free(root); struct TreeNode* node = (struct
return temp; TreeNode*)malloc(sizeof(struct TreeNode));
} node->val = val;
// Case 4: The node has two children node->left = NULL;
else { node->right = NULL;
struct TreeNode* temp = root->right; return node;
// Find the smallest node in the right subtree (in-order }
successor)
while (temp->left) { // Function to solve and construct the BST from preorder
temp = temp->left; traversal
} struct TreeNode* solve(int* preorder, int* index, int size, int h) {
// Replace the current node's left subtree to the // If index is out of bounds or current value exceeds the
successor's left upper bound (h)
temp->left = root->left; if (*index == size || preorder[*index] > h) return NULL;
struct TreeNode* newRoot = root->right;
free(root); // Create a new TreeNode with the current value
return newRoot; struct TreeNode* root = newTreeNode(preorder[*index]);
} (*index)++; // Increment the index to process the next
} element

return root; // Recursively build the left and right subtrees


} root->left = solve(preorder, index, size, root->val);
root->right = solve(preorder, index, size, h);
// Helper function to perform in-order traversal and print the
tree return root;
void inorder(struct TreeNode* root) { }
if (root == NULL) return;
inorder(root->left); // Function to build a BST from preorder traversal
printf("%d ", root->val); struct TreeNode* bstFromPreorder(int* preorder, int size) {
inorder(root->right); int index = 0; // Initialize the index to 0
}
// Use INT_MAX as the upper bound for the initial root
int main() { return solve(preorder, &index, size, INT_MAX);
struct TreeNode* root = newTreeNode(5); }
root->left = newTreeNode(3);
root->right = newTreeNode(8); // Helper function to perform in-order traversal and print the
root->left->left = newTreeNode(2); tree
root->left->right = newTreeNode(4); void inorder(struct TreeNode* root) {
root->right->left = newTreeNode(6); if (root == NULL) return;
root->right->right = newTreeNode(10); inorder(root->left);
printf("%d ", root->val);
printf("Original Tree (in-order traversal):\n"); inorder(root->right);
inorder(root); }
printf("\n");
int main() {
int key = 3; // Preorder traversal array
root = deleteNode(root, key); int preorder[] = {8, 5, 1, 7, 10, 12};
int size = sizeof(preorder) / sizeof(preorder[0]);
printf("Tree after deleting node with value %d (in-order
traversal):\n", key); // Build the BST from the preorder array
inorder(root); struct TreeNode* root = bstFromPreorder(preorder, size);
printf("\n");
// Print the BST in in-order traversal
return 0; printf("Inorder traversal of the constructed BST:\n");
} inorder(root);
printf("\n"); return 0; }

You might also like