# c – Unival Tree Implementation

I have written some code to solve the following interview question. Please advise how it can be improved. Thanks in advance.

A unival tree (which stands for “universal value”) is a tree where all nodes under it have the same value. Given the root to a binary tree, count the number of unival subtrees.
For example, the following tree has 5 unival subtrees: Implementation:

``````#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>

typedef struct stTree
{
struct stTree * left;
struct stTree * right;
int value;
}

stTree;

stTree* createNode(int value)
{
stTree *node = malloc(sizeof *node);
node->left = NULL;
node->right = NULL;
node->value = value;

return node;
}

bool isTreeUniv(stTree *node)
{
bool flag = true;

if (!node)
return false;

if (node->right && node->right->value != node->value)
{
flag = false;
}

if (node->left && node->left->value != node->value)
{
flag = false;
}

return flag;
}

stTree* insertRight(stTree *currNode, int value)
{
stTree *node = malloc(sizeof *node);

currNode->right = node;
node->left = NULL;
node->right = NULL;
node->value = value;
return node;
}

stTree* insertLeft(stTree *currNode, int value)
{
stTree *node = malloc(sizeof *node);

currNode->left = node;
node->left = NULL;
node->right = NULL;
node->value = value;
return node;
}

unsigned int uTreeCount = 0;
void countUnivSubT(stTree *Node)
{
if (isTreeUniv(Node))
uTreeCount++;

if (Node->left)
countUnivSubT(Node->left);

if (Node->right)
countUnivSubT(Node->right);

}

int main(void)
{
//build a tree
stTree *rootNode = createNode(0);
insertLeft(rootNode, 1);
insertRight(rootNode, 0);

insertLeft(rootNode->right, 1);
insertRight(rootNode->right, 0);

insertLeft(rootNode->right->left, 1);
insertRight(rootNode->right->left, 1);

countUnivSubT(rootNode);
printf("total universal subree: %un", uTreeCount);

}
``````