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.
- Two nodes of a BST are swapped, correct the BST
- Find Leftmost and Rightmost node of BST from its given preorder traversal
- Root to leaf path sum equal to a given number in BST
- Find all the pairs with given sum in a BST | Set 2
- Print all nodes at distance K from given node: Iterative Approach
- Delete N nodes after M nodes of a linked list
- Append odd position nodes in reverse at the end of even positioned nodes in a Linked List
- Sum of K largest elements in BST using O(1) Extra space
- Print BST keys in the given range
- Print all nodes that are at distance k from a leaf node
- Find node U containing all nodes from a set V at atmost distance 1 from the path from root to U
- Node having maximum number of nodes less than its value in its subtree
- Count nodes from all lower levels smaller than minimum valued node of current level for every level in a Binary Tree
- A program to check if a binary tree is BST or not
- Smallest number in BST which is greater than or equal to N ( Iterative Approach)
- Check if the Binary Tree contains a balanced BST of size K
- Count of all possible Paths in a Tree such that Node X does not appear before Node Y
- Farthest distance of a Node from each Node of a Tree
- Linked List Sum of Nodes Between 0s
- Sum of leaf nodes at minimum level
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.