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:
- Print all nodes that are at distance k from a leaf node
- 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
- Linked List Sum of Nodes Between 0s
- Shortest distance between two nodes in BST
- Nodes from given two BSTs with sum equal to X
- Two nodes of a BST are swapped, correct the BST | Set-2
- Delete leaf nodes with value k
- Two nodes of a BST are swapped, correct the BST
- Connect nodes at same level
- Maximum element between two nodes of BST
- Count BST nodes that lie in a given range
- Product of all nodes in a Binary Tree
- Print nodes at k distance from root
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. 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.