I am trying to resolve following problem. Please advice which part of the code can be improved.
Given a binary tree and a sum, determine if the tree has a root-to-leaf path such that adding up all the values along the path equals the given sum.
Example: Given the below binary tree and sum = 22,
5
/ \
4 8
/ / \
11 13 4
/ \ \
7 2 1
return true, as there exist a root-to-leaf path 5->4->11->2 which sum is 22.
Implementation:
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
typedef struct stTree
{
struct stTree * left;
struct stTree * right;
int value;
} stTree;
struct stTestCase
{
stTree *root;
int sum;
bool result;
};
stTree* createNode(int value, stTree *leftNode, stTree *rightNode)
{
stTree *node = malloc(sizeof *node);
if (!node) abort();
node->left = leftNode;
node->right = rightNode;
node->value = value;
return node;
}
bool hasPathSum(const stTree *root, int sum)
{
if (!root) return false;
if (!root->left && !root->right)
{
if (sum == root->value)
return true;
else
return false;
}
return (hasPathSum(root->left, sum - root->value)
| hasPathSum(root->right, sum - root->value));
}
static stTree* findBottomLeft(stTree *node)
{
while (node->left)
node = node->left;
return node;
}
void freeTree(stTree *node)
{
if (!node) return true;
stTree *bottomLeft = findBottomLeft(node);
while (node)
{
if (node->right)
{
bottomLeft->left = node->right;
bottomLeft = findBottomLeft(bottomLeft);
}
stTree *old = node;
node = node->left;
free(old);
}
}
int main(void)
{
struct stTestCase test_cases[3]={
{
createNode(5,
createNode(4,
createNode(11,
createNode(7, NULL, NULL),
createNode(2, NULL, NULL)), NULL),
createNode(8,
createNode(13, NULL, NULL),
createNode(4, NULL,
createNode(1, NULL, NULL)))),
22,
true
},
{
createNode(5,
createNode(1,
createNode(11,
createNode(3, NULL, NULL),
createNode(2, NULL, NULL)), NULL),
createNode(7,
createNode(13, NULL, NULL),
createNode(4, NULL,
createNode(1, NULL, NULL)))),
22,
false
},
{
createNode(12,
createNode(4,
createNode(11,
createNode(7, NULL, NULL),
createNode(51, NULL, NULL)), NULL),
createNode(8,
createNode(13, NULL, NULL),
createNode(4, NULL,
createNode(6, NULL, NULL)))),
22,
false
}
};
for(int i=0; i<3; i++)
{
if (hasPathSum(test_cases[i].root, test_cases[i].sum) == test_cases[i].result)
printf("test case [%d], PASS\n", i);
else
printf("test case [%d], FAIL\n", i);
freeTree(test_cases[i].root);
}
}
RESULT:
test case [0], PASS
test case [1], PASS
test case [2], PASS