Sum of cousin nodes of a given node in a BST
Given a binary search tree and a number N, the task is to find the sum of the cousins of the given node N if a node with given value ‘N’ is present in the given BST otherwise print -1.
Input: Node = 12 Output: 40 Cousins are 18 and 22 Input: 19 Output: -1
Approach: Given below is the algorithm to solve the problem.
- Find the parent of the given node, if the node is not present return -1.
- Traverse in the tree, find the level of each node while traversal.
- If the level is the same as the given node. Check for the parent of that node, if the parent is different then add the node to the sum.
Below is the implementation of above approach:
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.