![]() |
VOOZH | about |
According to the property of a Binary tree, a node can have at most two children so there are three cases where a node can have two children, onechild, or no child, the task is to track the count of unique nodes and return the total number of unique nodes that have no child, one child, and two children. Given the root of the binary tree return a vector where arr[0] represents the total unique nodes that contain 0 children, arr[1] represents the total unique nodes having 1 child, and arr[2] represents the total unique nodes that have exactly two children.
Examples:
Input:
2
/ \
1 4
/ \ \
2 1 1
/ \
7 5Output: 4 1 2
Explanation: Nodes with no child are 2, 1, 7, and 5 and all these nodes have unique values so the count is 4. There is only 1 Node with 1 child i.e. 4 so the count will be 1 here.
Nodes with two children are 2 (root), 1 ( 2's child ), and 1 ( 4's child ), since 1 is repeating that's why only 2 (root) and 1 will be counted as unique nodes so the count will be 2 here.Input:
3
/ \
2 2Output: 1 0 1
Explanation: Nodes with no child are 2 and 2 so the unique node's count will be 1.
There is no node with 1 child so the count will be 0.
There is only 1 node with 2 children i.e. 3 (root node) so the count will be 1 here.
Approach: To solve the problem follow the below idea:
We can consider the different types of nodes as a pattern and use a hashmap to store every unique node's pattern.
Follow the steps to solve the problem:
Below code is the implementation of the above approach:
4 1 2
Time Complexity: O(N*logN), N For traversing the tree and LogN for map operations
Auxiliary Space: O(N), For hashmaps, at max, N values can be stored