![]() |
VOOZH | about |
Given a binary tree containing n nodes. The problem is to find the sum of all the parent node's which have a child node with value x.
Examples:
Input : Binary tree with x = 2: 4 / \ 2 5 / \ / \ 7 2 2 3 Output : 11 4 / \ 2 5 / \ / \ 7 2 2 3 The highlighted nodes (4, 2, 5) above are the nodes having 2 as a child node.
Algorithm:
sumOfParentOfX(root,sum,x) if root == NULL return if (root->left && root->left->data == x) || (root->right && root->right->data == x) sum += root->data sumOfParentOfX(root->left, sum, x) sumOfParentOfX(root->right, sum, x) sumOfParentOfXUtil(root,x) Declare sum = 0 sumOfParentOfX(root, sum, x) return sum
Implementation:
Sum = 11
Time Complexity: O(n).
Auxiliary space: O(n) for call stack as it is using recursion