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
- 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
- Delete leaf nodes with value k
- Count BST nodes that lie in a given range
- Connect nodes at same level
- Two nodes of a BST are swapped, correct the BST
- Two nodes of a BST are swapped, correct the BST | Set-2
- Nodes from given two BSTs with sum equal to X
- Shortest distance between two nodes in BST
- Delete all the nodes from the list that are greater than x
- Sum of all nodes at Kth level in a Binary Tree
- Product of all nodes in a Binary Tree
- Print nodes at k distance from root