![]() |
VOOZH | about |
Given an N-ary tree, find the number of siblings of given node x. Assume that x exists in the given n-ary tree.
Example :
Input : 30 Output : 3
Approach: For every node in the given n-ary tree, push the children of the current node in the queue. While adding the children of current node in queue, check if any children is equal to the given value x or not. If yes, then return the number of siblings of x.
Below is the implementation of the above idea :
1
Complexity Analysis:
Create a hash map to store the parent of each node.
For each node in the tree, map it to its parent in the hash map.
Given the node for which you want to find the number of siblings, look up its parent in the hash map.
If the parent is not found, return 0 as the node has no siblings.
If the parent is found, count the number of children the parent has.
Return the count minus 1 as the given node is included in the count.
Note: This algorithm assumes that the parent array is complete and accurately represents the n-ary tree.
The number of siblings for node 4 is: 2
In this implementation, the findSiblingCount function takes a node and the tree represented as a hash map as inputs and returns the number of siblings the node has. If the node is not found in the tree map, it returns 0 as the node has no siblings. If the node is found, the function looks up the parent of the node in the tree map and returns the number of children the parent has minus 1, which represents the number of siblings the node has.
The time complexity of the above code is O(1) because the findSiblingCount function takes constant time to find the number of siblings of a given node. This is because the hash map is used to store the parent of each node, so looking up the parent of a given node takes constant time. The same holds true for counting the number of children the parent has.
The space complexity of the above code is O(n), where n is the number of nodes in the n-ary tree. This is because the hash map is used to store the parent of each node and the children of each parent, so the space required is proportional to the number of nodes in the tree.
Note: The space complexity assumes that the hash map is used to represent the tree and the number of children each node has is constant, so the space used is linear in the number of nodes. If the number of children each node has is not constant, the space complexity would be higher.