Print cousins of a given node in Binary Tree - GeeksforGeeks
Given a binary tree and a node, print all cousins of given node. Note that siblings should not be printed.
Read full article from Print cousins of a given node in Binary Tree - GeeksforGeeks
Given a binary tree and a node, print all cousins of given node. Note that siblings should not be printed.
Input : root of below tree 1 / \ 2 3 / \ / \ 4 5 6 7 and pointer to a node say 5. Output : 6, 7
We strongly recommend you to minimize your browser and try this yourself first.
The idea to first find level of given node using the approach discussed here. Once we have found level, we can print all nodes at a given level using the approach discussed here. The only thing to take care of is, sibling should not be printed. To handle this, we change the printing function to first check for sibling and print node only if it is not sibling.
/* It returns level of the node if it is present
in tree, otherwise returns 0.*/
int
getLevel(Node *root, Node *node,
int
level)
{
// base cases
if
(root == NULL)
return
0;
if
(root == node)
return
level;
// If node is present in left subtree
int
downlevel = getLevel(root->left, node, level+1);
if
(downlevel != 0)
return
downlevel;
// If node is not present in left subtree
return
getLevel(root->right, node, level+1);
}
/* Print nodes at a given level such that sibling of
node is not printed if it exists */
void
printGivenLevel(Node* root, Node *node,
int
level)
{
// Base cases
if
(root == NULL || level < 2)
return
;
// If current node is parent of a node with
// given level
if
(level == 2)
{
if
(root->left == node || root->right == node)
return
;
if
(root->left)
printf
(
"%d "
, root->left->data);
if
(root->right)
printf
(
"%d "
, root->right->data);
}
// Recur for left and right subtrees
else
if
(level > 2)
{
printGivenLevel(root->left, node, level-1);
printGivenLevel(root->right, node, level-1);
}
}
// This function prints cousins of a given node
void
printCousins(Node *root, Node *node)
{
// Get level of given node
int
level = getLevel(root, node, 1);
// Print nodes of given level.
printGivenLevel(root, node, level);
}
Read full article from Print cousins of a given node in Binary Tree - GeeksforGeeks