Given an integer X and a binary tree, the task is to count the number of triplet triplets of nodes such that their sum is greater than X and they have a grandparent -> parent -> child relationship.
Input: X = 100 10 / \ 1 22 / \ / \ 35 4 15 67 / \ / \ / \ / \ 57 38 9 10 110 312 131 414 / \ 8 39 Output: 6 The triplets are: 22 -> 15 -> 110 22 -> 15 -> 312 15 -> 312 -> 8 22 -> 67 -> 131 22 -> 67 -> 414 67 -> 414 -> 39
Approach: The problem can be solved using rolling sum up approach with rolling period as 3 (grandparent -> parent -> child)
- Traverse the tree in preorder or postorder (INORDER WON’T WORK)
- Maintain a stack where we maintain rolling sum with rolling period as 3
- Whenever we have more than 3 elements in stack and if the top most value is greater than X, we increment result by 1.
- When we move up the recursion tree we do a POP operation on stack so that all the rolling sums of lower levels get removed from the stack.
Below is the implementation of the above approach:
- Count the Number of Binary Search Trees present in a Binary Tree
- Count Non-Leaf nodes in a Binary Tree
- Count pairs in a binary tree whose sum is equal to a given value x
- Count nodes with two children at level L in a Binary Tree
- Program to count leaf nodes in a binary tree
- Count full nodes in a Binary tree (Iterative and Recursive)
- Iterative program to count leaf nodes in a Binary Tree
- Count half nodes in a Binary tree (Iterative and Recursive)
- Complexity of different operations in Binary tree, Binary Search Tree and AVL tree
- Minimum swap required to convert binary tree to binary search tree
- Count number of triplets in an array having sum in the range [a, b]
- Check whether a binary tree is a full binary tree or not | Iterative Approach
- Count triplets in a sorted doubly linked list whose product is equal to a given value x
- Convert a Binary Tree to Threaded binary tree | Set 2 (Efficient)
- Convert a Binary Tree to Threaded binary tree | Set 1 (Using Queue)
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to email@example.com. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.