Subtree altaf
Thu Sep 14 2023 18:49:42 GMT+0000 (Coordinated Universal Time)
Saved by @Astik
#include <stdio.h> #include <stdbool.h> #include <stdlib.h> // Structure for a binary tree node struct TreeNode { int data; struct TreeNode* left; struct TreeNode* right; }; // Function to create a new binary tree node struct TreeNode* createNode(int data) { struct TreeNode* newNode = (struct TreeNode*)malloc(sizeof(struct TreeNode)); newNode->data = data; newNode->left = NULL; newNode->right = NULL; return newNode; } // Function to check if two binary trees are identical bool areIdentical(struct TreeNode* tree1, struct TreeNode* tree2) { if (tree1 == NULL && tree2 == NULL) return true; if (tree1 == NULL || tree2 == NULL) return false; return (tree1->data == tree2->data) && areIdentical(tree1->left, tree2->left) && areIdentical(tree1->right, tree2->right); } // Function to check if tree2 is a subtree of tree1 bool isSubtree(struct TreeNode* tree1, struct TreeNode* tree2) { if (tree1 == NULL) return false; if (areIdentical(tree1, tree2)) return true; return isSubtree(tree1->left, tree2) || isSubtree(tree1->right, tree2); } // Function to build a binary tree from user input struct TreeNode* buildTree() { int data; printf("Enter data (or -1 to create an empty node): "); scanf("%d", &data); if (data == -1) return NULL; struct TreeNode* newNode = createNode(data); printf("Enter left subtree for node %d:\n", data); newNode->left = buildTree(); printf("Enter right subtree for node %d:\n", data); newNode->right = buildTree(); return newNode; } int main() { printf("Create the main tree:\n"); struct TreeNode* mainTree = buildTree(); printf("Create the subtree to check:\n"); struct TreeNode* subtree = buildTree(); // Check if the subtree is present in the main tree if (isSubtree(mainTree, subtree)) printf("The subtree is present in the main tree.\n"); else printf("The subtree is not present in the main tree.\n"); return 0; }
Comments