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.
- Print all nodes that are at distance k from a leaf node
- Print all nodes at distance K from given node: Iterative Approach
- Implementing a BST where every node stores the maximum number of nodes in the path till any leaf
- Append odd position nodes in reverse at the end of even positioned nodes in a Linked List
- Delete N nodes after M nodes of a linked list
- 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
- Maximum element between two nodes of BST
- Two nodes of a BST are swapped, correct the BST | Set-2
- Nodes from given two BSTs with sum equal to X
- Count BST nodes that lie in a given range
- Delete leaf nodes with value k
- Shortest distance between two nodes in BST
- Two nodes of a BST are swapped, correct the BST
- Connect nodes at same level
- Print nodes at k distance from root
- Delete all the nodes from the list that are greater than x
- Count greater nodes in AVL tree
- Product of all nodes in a Binary Tree
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.