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)
- 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
- Kth ancestor of a node in binary tree | Set 2
- K-th ancestor of a node in Binary Tree
- Search a node in Binary Tree
- Preorder predecessor of a Node in Binary Tree
- Preorder Successor of a Node in Binary Tree
- Total sum except adjacent of a given node in a Binary Tree
- Inorder Successor of a node in Binary Tree
- Find n-th node in Preorder traversal of a Binary Tree
- Find the node with maximum value in a Binary Search Tree
- Get level of a node in binary tree | iterative approach
- Print the nodes of binary tree as they become the leaf node
- Sort the path from root to a given node in a Binary Tree