Posted on by Kalkicode
Code Binary Tree

Check for continuous binary tree in c

C program for Check for continuous binary tree. Here more information.

// Include header file
#include <stdio.h>
#include <stdlib.h>
/* 
  C program for
  Check if binary tree is continuous 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 absValue(int num)
{
	if (num < 0)
	{
		return -num;
	}
	return num;
}
// Check tree is continuous or not
int isContinuous(TreeNode * node)
{
	if (node != NULL)
	{
		if ((node->left != NULL && 
            absValue(node->data - node->left->data) != 1) || 
            (node->right != NULL && 
             absValue(node->data - node->right->data) != 1))
		{
			// Case
			// When fail continuous tree rule
			return 0;
		}
		if (isContinuous(node->left) && 
            isContinuous(node->right))
		{
			return 1;
		}
		// When node value is not satisfied 
      	// continuous tree properties
		return 0;
	}
	return 1;
}
int main()
{
	// Create new tree
	BinaryTree * tree = getBinaryTree();
	/*  
	   Binary Tree
	   ------------
	       5
	     /   \
	    4     4
	   /     /  \
	  3     5    3
	   \
	    2
	        
	*/
	// Add tree node
	tree->root = getTreeNode(5);
	tree->root->left = getTreeNode(4);
	tree->root->right = getTreeNode(4);
	tree->root->left->left = getTreeNode(3);
	tree->root->right->right = getTreeNode(3);
	tree->root->right->left = getTreeNode(5);
	tree->root->left->left->right = getTreeNode(2);
	if (isContinuous(tree->root) == 1)
	{
		printf("Continuous Tree\n");
	}
	else
	{
		printf("Not Continuous Tree\n");
	}
	// Case 2
	/* 
	       5
	     /   \
	    4     4
	   /     /  \
	  3     5    3
	   \
	    1  <--- change value
	        
	*/
	tree->root->left->left->right->data = 1;
	if (isContinuous(tree->root) == 1)
	{
		printf("Continuous Tree\n");
	}
	else
	{
		printf("Not Continuous Tree\n");
	}
}

Output

Continuous Tree
Not Continuous Tree

Comment

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