#include <stdio.h>
#include <stdlib.h>
// Definition for a binary tree node
struct TreeNode {
int val;
struct TreeNode *left;
struct TreeNode *right;
};
// Function to create a new binary tree node
struct TreeNode *createNode(int val) {
struct TreeNode *newNode = (struct TreeNode *)malloc(sizeof(struct TreeNode));
if (newNode == NULL) {
printf("Memory allocation failed\n");
exit(1);
}
newNode->val = val;
newNode->left = NULL;
newNode->right = NULL;
return newNode;
}
// Function to merge two binary trees
struct TreeNode *mergeTrees(struct TreeNode *t1, struct TreeNode *t2) {
if (t1 == NULL)
return t2;
if (t2 == NULL)
return t1;
t1->left = mergeTrees(t1->left, t2->left);
t1->right = mergeTrees(t1->right, t2->right);
return t1;
}
// Function to construct binary tree from forest
struct TreeNode *constructBinaryTreeFromForest(struct TreeNode **trees, int numTrees) {
if (numTrees == 0)
return NULL;
if (numTrees == 1)
return trees[0];
struct TreeNode *mergedTree = trees[0];
int i;
for (i = 1; i < numTrees; i++) {
mergedTree = mergeTrees(mergedTree, trees[i]);
}
return mergedTree;
}
// Function to print inorder traversal of binary tree
void inorderTraversal(struct TreeNode *root) {
if (root != NULL) {
inorderTraversal(root->left);
printf("%d ", root->val);
inorderTraversal(root->right);
}
}
int main() {
// Sample trees in the forest
struct TreeNode *tree1 = createNode(1);
tree1->left = createNode(2);
tree1->right = createNode(3);
struct TreeNode *tree2 = createNode(4);
tree2->left = createNode(5);
struct TreeNode *tree3 = createNode(6);
tree3->right = createNode(7);
// Array of trees in the forest
struct TreeNode *forest[] = {tree1, tree2, tree3};
int numTrees = sizeof(forest) / sizeof(forest[0]);
// Construct binary tree from the forest
struct TreeNode *binaryTree = constructBinaryTreeFromForest(forest, numTrees);
// Print inorder traversal of the constructed binary tree
printf("Inorder Traversal of Constructed Binary Tree:\n");
inorderTraversal(binaryTree);
printf("\n");
return 0;
}
To embed this project on your website, copy the following code and paste it into your website's HTML: