|
| 1 | +/** |
| 2 | + * Problem: Determine if a tree is sum tree. |
| 3 | + * A SumTree is a Binary Tree where the value of a node is equal to sum of the nodes present in its left subtree and right subtree. |
| 4 | + * An empty tree is SumTree and sum of an empty tree can be considered as 0. |
| 5 | + * A leaf node is also considered as SumTree. |
| 6 | + * |
| 7 | + * 26 |
| 8 | + * / \ |
| 9 | + * 10 3 |
| 10 | + * / \ \ |
| 11 | + * 4 6 3 |
| 12 | + */ |
| 13 | +#include <iostream> |
| 14 | + |
| 15 | +struct Node { |
| 16 | + /* data */ |
| 17 | + int data; |
| 18 | + Node * left; |
| 19 | + Node * right; |
| 20 | + Node( int d ) |
| 21 | + : data{ d }, left{ nullptr }, right{ nullptr } { } |
| 22 | +}; |
| 23 | + |
| 24 | +/** |
| 25 | + * addTree - Adds the contents of the tree |
| 26 | + * @param root |
| 27 | + * @return total of contents of tree |
| 28 | + */ |
| 29 | +int addTree( Node * root ) { |
| 30 | + if ( root == nullptr ) { |
| 31 | + return 0; |
| 32 | + } |
| 33 | + return (addTree(root->left) + root->data + addTree(root->right)) ; |
| 34 | +} |
| 35 | + |
| 36 | +bool sumTree( Node * root ) |
| 37 | +{ |
| 38 | + if ( root == nullptr ) { |
| 39 | + return true; |
| 40 | + } |
| 41 | + else if ( root->left == nullptr && root->right == nullptr ) { |
| 42 | + return true; |
| 43 | + } |
| 44 | + else { |
| 45 | + if ((addTree(root->left) + addTree(root->right) == root->data) && |
| 46 | + sumTree(root->left) && sumTree(root->right)) { |
| 47 | + return true; |
| 48 | + } else { |
| 49 | + return false; |
| 50 | + } |
| 51 | + } |
| 52 | +} |
| 53 | + |
| 54 | +void inorder(Node * root) |
| 55 | +{ |
| 56 | + if ( root ) { |
| 57 | + inorder(root->left); |
| 58 | + std::cout << root->data << " "; |
| 59 | + inorder(root->right); |
| 60 | + } |
| 61 | +} |
| 62 | + |
| 63 | +int main() |
| 64 | +{ |
| 65 | +/** |
| 66 | + * 26 |
| 67 | + * / \ |
| 68 | + * 10 3 |
| 69 | + * / \ \ |
| 70 | + * 4 6 3 |
| 71 | + */ |
| 72 | + Node * root = new Node(26); |
| 73 | + root->left = new Node(10); |
| 74 | + root->right = new Node(3); |
| 75 | + root->left->left = new Node(4); |
| 76 | + root->left->right = new Node(6); |
| 77 | + root->right->right = new Node(3); |
| 78 | + std::cout << "Inorder of the tree is :"; |
| 79 | + inorder(root); |
| 80 | + std::cout << std::endl; |
| 81 | + std::cout << "Is above tree sum-tree? : "; |
| 82 | + std::cout << ( sumTree(root) ? "Yes\n" : "No\n" ); |
| 83 | + return 0; |
| 84 | +} |
0 commit comments