Given a binary tree and data value of a node. The task is to find the sum of cousin nodes of given node. If given node has no cousins then return -1.
Note: It is given that all nodes have distinct values and the given node exists in the tree.
Input: 1 / \ 3 7 / \ / \ 6 5 4 13 / / \ 10 17 15 key = 13 Output: 11 Cousin nodes are 5 and 6 which gives sum 11. Input: 1 / \ 3 7 / \ / \ 6 5 4 13 / / \ 10 17 15 key = 7 Output: -1 No cousin nodes of node having value 7.
Approach: The approach is to do a level order traversal of the tree. While performing level order traversal, find the sum of child nodes of next level. Add a child node’s value to the sum and check if either of the children nodes is the target node or not. If yes, then do not add the value of either child to the sum. After traversing current level if the target node is present in next level, then end the level order traversal and sum found is the sum of cousin nodes.
Below is the implementation of the above approach:
Time Complexity: O(N)
Auxiliary Space: O(N)
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 cousins of a given node in Binary Tree | Single Traversal
- Check if two nodes are cousins in a Binary Tree
- Check if two nodes are cousins in a Binary Tree | Set-2
- Maximum sub-tree sum in a Binary Tree such that the sub-tree is also a BST
- Check whether a given binary tree is skewed binary tree or not?
- Total sum except adjacent of a given node in a Binary Tree
- Check if max sum level of Binary tree divides tree into two equal sum halves
- Find parent of given node in a Binary Tree with given postorder traversal
- Check whether a binary tree is a full binary tree or not | Iterative Approach
- Check if a binary tree is subtree of another binary tree using preorder traversal : Iterative
- Convert a Binary Tree such that every node stores the sum of all nodes in its right subtree
- Sort the path from root to a given node in a Binary Tree
- Find the maximum node at a given level in a binary tree
- Get last node of the binary tree following given pattern starting from X
- Print all the nodes except the leftmost node in every level of the given binary tree
- Find the color of given node in an infinite binary tree
- Find the parent of a node in the given binary tree
- Deletion of a given node K in a Binary Tree using Level Order Traversal
- Given level order traversal of a Binary Tree, check if the Tree is a Min-Heap
- Print Binary Tree levels in sorted order | Set 3 (Tree given as array)
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.