Check for foldable binary tree in c
C program for Check for foldable binary tree. Here problem description and other solutions.
// Include header file
#include <stdio.h>
#include <stdlib.h>
/*
C program for
Check if binary tree is foldable binary tree
Using recursion
*/
// Binary Tree Node
typedef struct TreeNode
{
// Define useful field of TreeNode
int data;
struct TreeNode * left;
struct TreeNode * right;
}TreeNode;
TreeNode * getTreeNode(int data)
{
// Create dynamic memory of TreeNode
TreeNode * ref =
(TreeNode * ) malloc(sizeof(TreeNode));
if (ref == NULL)
{
// Failed to create memory
return NULL;
}
// Set node value
ref->data = data;
ref->left = NULL;
ref->right = NULL;
return ref;
}
typedef struct BinaryTree
{
// Define useful field of BinaryTree
struct TreeNode * root;
}BinaryTree;
BinaryTree * getBinaryTree()
{
// Create dynamic memory of BinaryTree
BinaryTree * ref =
(BinaryTree * ) malloc(sizeof(BinaryTree));
if (ref == NULL)
{
// Failed to create memory
return NULL;
}
// Set initial tree root
ref->root = NULL;
return ref;
}
int isFoldable(TreeNode * leftRoot,
TreeNode * rightRoot)
{
if (leftRoot == NULL && rightRoot == NULL)
{
// When both node empty
return 1;
}
else if (leftRoot != NULL && rightRoot != NULL &&
isFoldable(leftRoot->left, rightRoot->right) &&
isFoldable(leftRoot->right, rightRoot->left))
{
// When
// Valid the properties of foldable tree
return 1;
}
// Fail case
return 0;
}
// Display tree element inorder form
void inorder(TreeNode * node)
{
if (node != NULL)
{
// Visit to left subtree
inorder(node->left);
// Print node value
printf(" %d", node->data);
// Visit to right subtree
inorder(node->right);
}
}
int main()
{
// Create new tree
BinaryTree * tree = getBinaryTree();
/*
Binary Tree
-----------------------
5
/ \
7 4
/ \
1 2
\ /
2 5
*/
// Binary tree nodes
tree->root = getTreeNode(5);
tree->root->left = getTreeNode(7);
tree->root->right = getTreeNode(4);
tree->root->left->left = getTreeNode(1);
tree->root->right->right = getTreeNode(2);
tree->root->right->right->left = getTreeNode(5);
tree->root->left->left->right = getTreeNode(2);
// Display Tree elements
inorder(tree->root);
int result = isFoldable(tree->root->left,
tree->root->right);
if (result == 1)
{
printf("\n Foldable Tree\n");
}
else
{
printf("\n Not Foldable Tree\n");
}
/*
5
/ \
7 4
/ \
1 2
\ /
2 5
\
3
*/
// Case 2
tree->root->left->left->right->right = getTreeNode(3);
inorder(tree->root);
result = isFoldable(tree->root->left,
tree->root->right);
if (result == 1)
{
printf("\n Foldable Tree\n");
}
else
{
printf("\n Not Foldable Tree\n");
}
}
Output
1 2 7 5 4 5 2
Foldable Tree
1 2 3 7 5 4 5 2
Not Foldable Tree
Please share your knowledge to improve code and content standard. Also submit your doubts, and test case. We improve by your feedback. We will try to resolve your query as soon as possible.
New Comment