|
| 1 | +#include <stdio.h> |
| 2 | +#include <stdlib.h> |
| 3 | + |
| 4 | +struct TreeNode { |
| 5 | + int value; |
| 6 | + struct TreeNode* left; |
| 7 | + struct TreeNode* right; |
| 8 | +}; |
| 9 | + |
| 10 | +struct TreeNode* createNode(int val) { |
| 11 | + struct TreeNode* newNode = (struct TreeNode*)malloc(sizeof(struct TreeNode)); |
| 12 | + newNode->value = val; |
| 13 | + newNode->left = NULL; |
| 14 | + newNode->right = NULL; |
| 15 | + return newNode; |
| 16 | +} |
| 17 | + |
| 18 | +int isSumTree(struct TreeNode* root, int* sum) { |
| 19 | + // An empty tree is a Sum Tree |
| 20 | + if (root == NULL) { |
| 21 | + *sum = 0; |
| 22 | + return 1; // true |
| 23 | + } |
| 24 | + |
| 25 | + // Leaf nodes are Sum Trees |
| 26 | + if (root->left == NULL && root->right == NULL) { |
| 27 | + *sum = root->value; |
| 28 | + return 1; // true |
| 29 | + } |
| 30 | + |
| 31 | + int leftSum = 0, rightSum = 0; |
| 32 | + |
| 33 | + // Recursively check the left and right subtrees |
| 34 | + int leftIsSumTree = isSumTree(root->left, &leftSum); |
| 35 | + int rightIsSumTree = isSumTree(root->right, &rightSum); |
| 36 | + |
| 37 | + // The current node's value should equal the sum of left and right subtrees |
| 38 | + *sum = leftSum + rightSum + root->value; |
| 39 | + |
| 40 | + return leftIsSumTree && rightIsSumTree && (root->value == leftSum + rightSum); |
| 41 | +} |
| 42 | + |
| 43 | +// Helper function to initiate the check |
| 44 | +int isSumTreeWrapper(struct TreeNode* root) { |
| 45 | + int sum = 0; |
| 46 | + return isSumTree(root, &sum); |
| 47 | +} |
| 48 | + |
| 49 | +int main() { |
| 50 | + struct TreeNode* root = createNode(26); |
| 51 | + root->left = createNode(10); |
| 52 | + root->right = createNode(3); |
| 53 | + root->left->left = createNode(4); |
| 54 | + root->left->right = createNode(6); |
| 55 | + root->right->right = createNode(3); |
| 56 | + |
| 57 | + if (isSumTreeWrapper(root)) { |
| 58 | + printf("The binary tree is a Sum Tree.\n"); |
| 59 | + } else { |
| 60 | + printf("The binary tree is NOT a Sum Tree.\n"); |
| 61 | + } |
| 62 | + |
| 63 | + return 0; |
| 64 | +} |
0 commit comments